用canvas标签getElementById为null

天,用了火狐和360都告诉我canvas是null,这种最简单的怎么还能娶不到啊,哪位大神解答一下
图片说明

4个回答

script放到canvas下面,要不js代码放到window.onload里面,放上面你的canvas都还没生成

把script和canvas的位置换换,canvas那一行放到上面去

加个window.onload

script和canvas的位置交换,有时候的确会有这种问题,还有就是你的body和head在哪

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
html <canvas>标签的使用

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> <style type="text/css"> body{ background:black; } #c1{ background:white; } span{ color:white; } </style> <script> window.onload=function() { var oC = document.getElementById("c1") ; var oGC = oC.getContext('2d') ; var num = 0; oGC.translate(100,100); setInterval(function(){ num++; oGC.save(); oGC.clearRect(0,0,oC.width,oC.height); oGC.rotate(num*Math.PI/180); oGC.fillRect(0,0,100,100); oGC.restore(); },30); } </script> </head> <body> <canvas id="c1" width="400" height="400"> <span>不支持canvas浏览器</span> </canvas> </body> </html> 做了一个以坐标(100,100)为中心点旋转的小方块,显示效果不正常,请各位老师指教哪里有错误,谢谢!

在RGraph中this.canvas为null

<div class="post-text" itemprop="text"> <p>Whenever I am trying to update my chart through AJAX by clicking a button, I am getting following error:</p> <pre><code>TypeError: this.canvas is null this.context = this.canvas.getContext('2d'); RGraph.bar.js (line 49, col 9) </code></pre> <p>I tried various solutions but nothing worked for me. Here's are my two files which are being used in this process:</p> <p><strong>index.php:</strong></p> <pre><code>&lt;?php include("includes/db-config.php"); $query = "SELECT * FROM `tb_daily_statistics`"; $rs = mysqli_query($con, $query); $labels = array(); $data = array(); while($row = mysqli_fetch_array($rs)) { $labels[] = $row['day']; $data[] = $row['statistics']; } // Now you can aggregate all the data into one string $data_string = "[" . implode(", ", $data) . "]"; $labels_string = "['" . implode("', '", $labels) . "']"; ?&gt; &lt;!DOCTYPE HTML&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;title&gt;RGraph Charts&lt;/title&gt; &lt;script type="text/javascript" src="js/jquery-1.12.4.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="js/RGraph/RGraph.common.core.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="js/RGraph/RGraph.bar.js"&gt;&lt;/script&gt; &lt;!--[if lt IE 9]&gt;&lt;script src="js/RGraph/excanvas.js"&gt;&lt;/script&gt;&lt;![endif]--&gt; &lt;script type="text/javascript"&gt; $(document).ready(function (){ var bar = new RGraph.Bar({ id: 'mycanvas', data: &lt;?php echo $data_string; ?&gt;, options: { labels: &lt;?php echo $labels_string; ?&gt;, gutter: { left: 50 } } }).draw() $("#btnstats").click(function(){ var order_by = $(this).data("order"); //alert(order_by); // Reset the canvas RGraph.Reset(document.getElementById("mycanvas")); // Prepare data to send over server data = 'order_by='+order_by; RGraph.AJAX.getJSON('ajax/update-chart.php?'+data, draw_graph); }) }); // This is the AJAX callback function. It splits up the response, converts it to numbers and then creates the chart. function draw_graph(json) { // Set the JSON on the window object so that the button below can show it to the user. //window.__json__ = json; //$p(window.__json__); // Reset the canvas RGraph.Reset(document.getElementById("mycanvas")); // Now draw the chart var bar = new RGraph.Bar({ id: 'mycanvas', data: json.data, options: { labels: json.labels, gutter: { left: 50 } } }).draw() } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;canvas id="mycanvas" width="600" height="250"&gt;[No canvas support]&lt;/canvas&gt; &lt;br /&gt; &lt;input type="button" id="btnstats" value="Order By Stats" data-order="statistics" /&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>update-chart.php:</strong></p> <pre><code>&lt;?php require_once '../includes/db-config.php'; /* echo "&lt;pre&gt;"; print_r($_GET); echo "&lt;pre&gt;"; */ // Order by day if(isset($_GET['order_by']) &amp;&amp; $_GET['order_by'] == "statistics") { $order_by = $_GET['order_by']; $query = "SELECT * FROM `tb_daily_statistics` "; $query .= "ORDER BY " . $order_by; $rs = mysqli_query($con, $query); $labels = array(); $data = array(); while($row = mysqli_fetch_array($rs)) { $labels[] = $row['day']; $data[] = $row['statistics']; } // Now you can aggregate all the data into one string $data_string = "[" . implode(", ", $data) . "]"; $labels_string = "['" . implode("', '", $labels) . "']"; echo json_encode(array('data' =&gt; $data_string, 'labels' =&gt; $labels_string)); } ?&gt; </code></pre> <p>The response from server is fine. Here's what I am receiving:</p> <pre><code>{"data":"[64, 75, 84, 94, 95, 98, 124]","labels":"['Wed', 'Fri', 'Sun', 'Thu', 'Tue', 'Sat', 'Mon']" } </code></pre> <p>What could be the issue?</p> </div>

js 'getContext' of null

Uncaught TypeError: Cannot read property 'getContext' of null 才接触js,网上搜了很久没找到有用的,为什么我这个图片加载不出来 ``` <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>哈哈哈哈哈</title> </head> <body> <canvas id="'myCanvas" width="200" height="400"style="border:1px solid #c3c3c3;"> </canvas> <script> var canvas = document.getElementById('myCanvas'); var context = canvas.getContext('2d'); var img = new Image(); img.onload = function(){ context.drawImage(img,0,0); }; img.src='uu.png'; </script> </body> </html> ```

getelementById获取不到页面元素

![图片说明](https://img-ask.csdn.net/upload/201903/14/1552548011_113681.png) ![图片说明](https://img-ask.csdn.net/upload/201903/14/1552548019_5727.png) <br><br> 获取不到页面的元素,然而同时获取的“cName”就能获取的到。尝试过将js放在最后加载,但是仍获取不到元素。 </br> **前端页面** <br> ``` <div class="modal-body"> <ul id="BranchType" class="nav nav-tabs"> <li class="active" id="applyMergeLi "> <a id="applyMergeA" href="#ApplyMerge" onclick=setCookieApplyMerge() data-toggle="tab">申请合入</a> </li> <li id="applyPublishLi " class="active1" > <a id="applyPublisA" href="#ApplyPublish" onclick=setCookieApplyPublish() data-toggle="tab">申请发布</a> </li> <li id="mergeReviewLogLi" class="active2"> <a id="mergeReviewLogA" href="#MergeReviewLog" onclick=setCookieMergeReviewLog() data-toggle="tab">合入审批记录</a> </li> <li id="publishReviewLogLi" class="active3" > <a id="publishReviewLogA" href="#PublishReviewLog" onclick=setCookiePublishReviewLog() data-toggle="tab">发布审批记录</a> </li> </ul> ``` </br> **后台common.js** <br> ``` function hasClass( elementOne,cName ) { if (className==null){ return false; } return !!elementOne.className.match( new RegExp( "(\\s|^)" + cName + "(\\s|$)") ); // ( \\s|^ ) 判断前面是否有空格 (\\s | $ )判断后面是否有空格 两个感叹号为转换为布尔值 以方便做判断 } function addClass( elementOne,cName ) { if( !hasClass( elementOne,cName ) ){ elementOne.className += " " + cName; }; } function removeClass( elementOne,cName ) { if( hasClass( elementOne,cName ) ){ elementOne.className = elementOne.className.replace( new RegExp( "(\\s|^)" + cName + "(\\s|$)" )," " ); // replace方法是替换 }; } ``` <br> **方法调用部分** <br> ``` function onloadApplyPage() { var applyInfoPage = getCookie("applyInfoPage"); var applyMergeLi = document.getElementById("applyMergeLi"); var applyPublishLi = document.getElementById("applyPublishLi"); var mergeReviewLogLi = document.getElementById("mergeReviewLogLi"); var publishReviewLogLi = document.getElementById("publishReviewLogLi"); var ApplyMerge = document.getElementById("ApplyMerge"); var ApplyPublish = document.getElementById("ApplyPublish"); var MergeReviewLog = document.getElementById("MergeReviewLog"); var PublishReviewLog = document.getElementById("PublishReviewLog"); if(applyInfoPage==1) { //为这个类移除属性 addClass(applyMergeLi,"active"); removeClass(applyPublishLi,"active"); removeClass(mergeReviewLogLi,"active"); removeClass(publishReviewLogLi,"active"); $("#applyMergeA").attr("aria-expanded","true"); $("#applyPublishA").attr("aria-expanded","false"); $("#mergeReviewLogA").attr("aria-expanded","false"); $("#publishReviewLogA").attr("aria-expanded","false"); addClass(ApplyMerge,"active"); removeClass(ApplyPublish,"active"); removeClass(MergeReviewLog,"active"); removeClass(PublishReviewLog,"active"); } if(applyInfoPage==2) { //为这个类移除属性 removeClass(applyMergeLi,"active"); addClass(applyPublishLi,"active"); removeClass(mergeReviewLogLi,"active"); removeClass(publishReviewLogLi,"active"); $("#applyMergeA").attr("aria-expanded","false"); $("#applyPublishA").attr("aria-expanded","true"); $("#mergeReviewLogA").attr("aria-expanded","false"); $("#publishReviewLogA").attr("aria-expanded","false"); removeClass(ApplyMerge,"active"); addClass(ApplyPublish,"active"); removeClass(MergeReviewLog,"active"); removeClass(PublishReviewLog,"active"); } if(applyInfoPage==3) { //为这个类移除属性 removeClass(applyMergeLi,"active"); removeClass(applyPublishLi,"active"); addClass(mergeReviewLogLi,"active"); removeClass(publishReviewLogLi,"active"); $("#applyMergeA").attr("aria-expanded","false"); $("#applyPublishA").attr("aria-expanded","false"); $("#mergeReviewLogA").attr("aria-expanded","true"); $("#publishReviewLogA").attr("aria-expanded","false"); removeClass(ApplyMerge,"active"); removeClass(ApplyPublish,"active"); addClass(MergeReviewLog,"active"); removeClass(PublishReviewLog,"active"); } if(applyInfoPage==4) { //为这个类移除属性 removeClass(applyMergeLi,"active"); removeClass(applyPublishLi,"active"); removeClass(mergeReviewLogLi,"active"); addClass(publishReviewLogLi,"active"); $("#applyMergeA").attr("aria-expanded","false"); $("#applyPublishA").attr("aria-expanded","false"); $("#mergeReviewLogA").attr("aria-expanded","false"); $("#publishReviewLogA").attr("aria-expanded","true"); removeClass(ApplyMerge,"active"); removeClass(ApplyPublish,"active"); removeClass(MergeReviewLog,"active"); addClass(PublishReviewLog,"active"); } } ```

vue中用html2canvas转换图片 图片不完整 或有偏移 有空白区域

``` html部分 <div style="height: 312px;overflow:hidden"> <div class="parter" id="parter" ref="parter"> <div class="qrcode" id="qrcode"></div> <p class="copywriting">{{changeText}}</p> </div> </div> ``` ``` js部分 html2canvas(document.getElementById('parter'), { width: 300, height: 300, backgroundColor: null, useCORS: true, // 允许图片跨域 taintTest: true, // 在渲染前测试图片 timeout: 500 // 加载延时 }).then(canvas => { canvas.toBlob((blob) => { saveAs(blob, '桌贴.png') }) }) ``` ![图片说明](https://img-ask.csdn.net/upload/201908/03/1564815559_206721.png) 导出的图片网上偏移

FabricJS 在mac机器上对Canvas调整大小屏幕会闪烁

``` 我的HTML代码: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Ionic App</title> <!--script type="text/javascript" language='javascript' src="fabric.js"></script--> <script type="text/javascript" language='javascript' src="index.js"></script> <style type="text/css"> html, body { width: 100%; height: 100%; margin-top: 0px; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; } #left { float: left; width: 20%; height: 100%; border: 0px solid red; padding: 0px; margin: 0px; } #center { float: left; width: 80%; height: 100%; border: 0px solid green; } #canvasWrapper { overflow: scroll; background: #FFFFFF; } #canvas{ border: 0px solid black; } </style> </head> <body id='body'> <div id='left'> <button onclick="init()">Init Canvas</button> <input type="file" onchange="chooseImage(event)"/><br/> <button onclick="zoomIn()">Zoom In</button> <button onclick="zoomOut()">Zoom Out</button><br/> </div> <div id='center'> <div id='canvasWrapper' tabIndex='0'> <canvas id="canvas" ></canvas> </div> </div> </body> </html> index.js代码: /*! index.js 使用FabricJS对钡条逻辑封装的*/ // 0 1 2 3 4 5 6 7 8 9 10 var zoomArray = [0.33, 0.4, 0.5, 0.66, 0.8, 1, 1.25, 1.5, 2, 2.5, 3]; //缩放的比例,都是对称的 var zoomIndex = 5; //当前的zoomIndex var canvasWrapper = null; //Canvas的包裹物,当外部的window大小变化时候需要对它的宽度和高度设置 var canvas = null; //Canvas var fCanvas = null; //中间的Fabric.Canvas var backgroundBase64 = null; var backgroundImage = null; //背景fabric.Image var backgroundImageWidth = 0 //Canvas的宽度,由图片的宽度决定 var backgroundImageHeight = 0; //Canvas的高度,由图片的高度决定 //Canvas的属性 var canvasAttrs = { imageSmoothingEnabled: false, enableRetinaScaling: false, stopContextMenu: true, //Menu禁用 fireLeftClick: true, //左按键启用 fireMiddleClick: true, //滚动键启用 fireRightClick: false, //右按键禁用 //selectionColor: '#CC00FF', //selection的颜色 selectionLineWidth: 2, //selection的线宽 selection: true, //selection启动 selectionBorderColor: '#FFFF00',//selection边框颜色 selectionFullyContained: true, //只有当selection全部包含Canvas.Object的时候才会被选中 selectionKey: 'ctrlKey' //使用ctrlKey进行多选 }; //图片属性,中间Canvas的背景图和坐下那个图 var imageAttrs = { left: 0, top: 0, selectable: false, //设置不能被选中,这样就可以作为背景图了 hoverCursor: "default", //设置它的鼠标形状 crossOrigin: 'Anonymous' }; /*! * OK选择文件 */ function chooseImage(event) { var file = event.target.files[0]; var reader = new FileReader(); reader.onload = function(event) { var imgBase64 = event.target.result; backgroundBase64 = imgBase64; //构造数据 var data = {}; var dataMap = {}; data['partitions'] = []; data['items'] = []; data['filters'] = {}; dataMap['data'] = data; dataMap["base64"] = backgroundBase64; loadData(dataMap); } reader.readAsDataURL(file) } /*! * OK这是上来执行的函数 */ function init() { __initFilterBackend(); __initCanvasWrapper(); __initCanvas(); } function loadData(dataMap) { if (dataMap == null) return; //图片的Base64编码。这个值肯定是有的 backgroundBase64 = dataMap['base64']; //加载背景图 fabric.util.loadImage(backgroundBase64, function(img) { //背景图 backgroundImage = new fabric.Image(img, imageAttrs); backgroundImageWidth = backgroundImage.width; backgroundImageHeight = backgroundImage.height; fCanvas.setWidth(backgroundImageWidth); fCanvas.setHeight(backgroundImageHeight); fCanvas.add(backgroundImage); }); } /*! * OK放大按钮触发 */ function zoomIn() { var oldZoom = zoomArray[zoomIndex]; ++zoomIndex; if (zoomIndex > (zoomArray.length - 1)) { zoomIndex = (zoomArray.length - 1); //直接return掉,因为zoomIndex > (zoomArray.length - 1)说明之前的zoomIndex已经是数组最后一个了 return; } __zoom(oldZoom); } /*! * OK缩小按钮触发 */ function zoomOut() { var oldZoom = zoomArray[zoomIndex]; --zoomIndex; if (zoomIndex < 0) { zoomIndex = 0; //直接return掉,因为zoomIndex < 0说明之前的zoomIndex已经是0了 return; } __zoom(oldZoom); } /*! * OK初始化Filter后端。使用Canvas2dFilterBackend,因为如果用new fabric.WebglFilterBackend()会报错 */ function __initFilterBackend() { fabric.filterBackend = new fabric.Canvas2dFilterBackend(); } /*! * OK初始化CanvasWrapper */ function __initCanvasWrapper() { //如果已经初始话好了就直接return if (canvasWrapper != null) return; var centerDiv = window.document.getElementById('center'); var width = centerDiv.offsetWidth; var height = centerDiv.offsetHeight; canvasWrapper = window.document.getElementById('canvasWrapper'); //这里通过style的width和height里设置加上px,并且这里我不设置style的maxWidth和maxHeight //因为如果设置了maxWidth和maxHeight后当我们对里面的Canvas进行缩小的时候,如果里面的Canvas变的太小,这样 canvasWrapper.style.width = width + 'px'; canvasWrapper.style.height = height + 'px'; } /*! * OK初始化Canvas */ function __initCanvas() { //如果已经初始化好了就直接return if (fCanvas != null) return; canvas = window.document.getElementById('canvas'); //这里不设置宽度和高度,通过导入图片的宽高来设置 fCanvas = new fabric.Canvas(canvas, canvasAttrs); //单纯设置canvas.backgroundColor内容无效,必须和下面的canvas.add一起才会起效果 fCanvas.backgroundColor = 'black'; } /*! * OK缩放的核心函数 */ function __zoom(oldZoom) { //记录一开始的left和top值 //var scrollLeft = canvasWrapper.scrollLeft; //var scrollTop = canvasWrapper.scrollTop; //以下是放大缩小操作,重新设置放大缩小的比例 var zoom = zoomArray[zoomIndex]; //在指定的点进行缩放 fCanvas.setZoom(zoom); //!Important,加入对Canvas大小的设置,这样可以让CanvasWrapper也能进行调整 fCanvas.setWidth(backgroundImageWidth*zoom); fCanvas.setHeight(backgroundImageHeight*zoom); //放大完后要重新设置transform //var vpt = fCanvas.viewportTransform; //console.log('-----' + vpt[4] + ' and ' + vpt[5]); //vpt[4] = 0; //vpt[5] = 0; //fCanvas.requestRenderAll(); /* oldleft newLeft * --------- = --------- * oldZoom newZoom */ //canvasWrapper.scrollLeft = (scrollLeft*zoom)/oldZoom; //canvasWrapper.scrollTop = (scrollTop*zoom)/oldZoom; } ```

fileObj = document.getElementById("file").files[0]; 我想直接把地址给这个变量

``` <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>压缩图片demo</title> </head> <body> <img id="img" src=""> <input id="file" type="file" onchange="compress()"> </body> <script> // 对图片进行压缩 function compress() { if(typeof FileReader=='undifined')            //判断浏览器是否支持filereader      {         result.innerHTML="<p>抱歉,你的浏览器不支持 FileReader</p>";         return false;     }     var file=document.getElementById("file").files[0];     if(!/image\/\w+/.test(file.type))            //判断获取的是否为图片文件     {         alert("请确保文件为图像文件");         return false;     } fileObj = document.getElementById('file').files[0] //上传文件的对象 reader = new FileReader() reader.readAsDataURL(fileObj) reader.onload = function(e) { image = new Image() //新建一个img标签(还没嵌入DOM节点) image.src = e.target.result image.onload = function() { canvas = document.createElement('canvas'), context = canvas.getContext('2d'), imageWidth = image.width / 10, //压缩后图片的大小 imageHeight = image.height / 10, data = '' canvas.width = imageWidth canvas.height = imageHeight context.drawImage(image, 0, 0, imageWidth, imageHeight) data = canvas.toDataURL('image/jpeg') //压缩完成 document.getElementById('img').src = data } } } </script> </html> ``` 上面是压缩图片的案例,我 不想用按钮,想直接把“1.jpg”赋值给fileObj,请问该怎么办??

Canvas在AJAX调用时消失

<div class="post-text" itemprop="text"> <p>The canvas will disappear when I refresh the data with <strong>AJAX</strong></p> <p>This is my canvas script:</p> <pre><code>&lt;script language="javascript" type="text/javascript" defer&gt; // Global variable var img = null, needle = null, ctx = null, degrees = 0; //alert("I am an alert box!"); function clearCanvas() { // clear canvas // ctx.clearRect(0, 0, 200, 200); ctx.clearRect(0, 0, 320, 320); } function draw() { clearCanvas(); // Draw the compass onto the canvas ctx.drawImage(img, 0, 0); // Save the current drawing state ctx.save(); // Now move across and down half the // ctx.translate(100, 100); ctx.translate(160, 160); // Rotate around this point ctx.rotate(degrees * (Math.PI / 180)); degrees = &lt;?php echo round($windDirDeg,0);?&gt; // Draw the image back and up //ctx.drawImage(needle, -100, -100); ctx.drawImage(needle, -160, -160); // Restore the previous drawing state ctx.restore(); // Increment the angle of the needle by 5 degrees // Increase by 5 only if you want continuous rotation // put 0 if you don't want to rotate degrees += 0; } function imgLoaded() { // Image loaded event complete. Start the timer //setInterval(draw, 100); setInterval(draw, 160); } function init() { // Grab the compass element var canvas = document.getElementById('Compass'); // Canvas supported? if (canvas.getContext('2d')) { ctx = canvas.getContext('2d'); // Load the needle image needle = new Image(); needle.src = &lt;?php echo "'image/Arrow.$colSkin.png'";?&gt;; // Load the compass image img = new Image(); img.src = 'image/compass1.png'; img.onload = imgLoaded; } else { alert("Canvas not supported!"); } } &lt;/script&gt; </code></pre> <p>this is my ajax script</p> <pre><code>&lt;script type="text/javascript"&gt; function Ajax(){ var xmlHttp; try{ xmlHttp=new XMLHttpRequest();// Firefox, Opera 8.0+, Safari } catch (e){ try{ xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer } catch (e){ try{ xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } catch (e){ alert("No AJAX!?"); return false; } } } xmlHttp.onreadystatechange=function(){ if(xmlHttp.readyState==4){ document.getElementById('ReloadThis').innerHTML=xmlHttp.responseText; setTimeout('Ajax()',3000); } } xmlHttp.open("GET","Home.php",true); xmlHttp.send(null); } window.onload=function(){ setTimeout('Ajax()',3000); } &lt;/script&gt; </code></pre> <p>And this is my html code:</p> <pre><code>//run the ajax&lt;div id = "ReloadThis"&gt; &lt;body onLoad="init();"&gt; &lt;canvas id="Compass" width="320" height="320"&gt;&lt;/canvas&gt;//display the canvas &lt;/body&gt; &lt;/div&gt; </code></pre> </div>

canvas 截图,如何用下面这个函数得到图片数据。

var selectObj = null; function ImageCrop(canvasId, imageSource, x, y, width, height) { var canvas = $("#" + canvasId); if (canvas.length == 0 && imageSource) { return; } function canvasMouseDown(e) { StopSelect(e); canvas.css("cursor", "default"); } function canvasMouseMove(e) { var canvasOffset = canvas.offset(); var pageX = e.pageX || event.targetTouches[0].pageX; var pageY = e.pageY || event.targetTouches[0].pageY; iMouseX = Math.floor(pageX - canvasOffset.left); iMouseY = Math.floor(pageY - canvasOffset.top); canvas.css("cursor", "default"); if (selectObj.bDragAll) { canvas.css("cursor", "move"); canvas.data("drag", true); var cx = iMouseX - selectObj.px; cx = cx < 0 ? 0 : cx; mx = ctx.canvas.width - selectObj.w; cx = cx > mx ? mx : cx; selectObj.x = cx; var cy = iMouseY - selectObj.py; cy = cy < 0 ? 0 : cy; my = ctx.canvas.height - selectObj.h; cy = cy > my ? my : cy; selectObj.y = cy; } for (var i = 0; i < 4; i++) { selectObj.bHow[i] = false; selectObj.iCSize[i] = selectObj.csize; } // hovering over resize cubes if (iMouseX > selectObj.x - selectObj.csizeh && iMouseX < selectObj.x + selectObj.csizeh && iMouseY > selectObj.y - selectObj.csizeh && iMouseY < selectObj.y + selectObj.csizeh) { canvas.css("cursor", "pointer"); selectObj.bHow[0] = true; selectObj.iCSize[0] = selectObj.csizeh; } if (iMouseX > selectObj.x + selectObj.w - selectObj.csizeh && iMouseX < selectObj.x + selectObj.w + selectObj.csizeh && iMouseY > selectObj.y - selectObj.csizeh && iMouseY < selectObj.y + selectObj.csizeh) { canvas.css("cursor", "pointer"); selectObj.bHow[1] = true; selectObj.iCSize[1] = selectObj.csizeh; } if (iMouseX > selectObj.x + selectObj.w - selectObj.csizeh && iMouseX < selectObj.x + selectObj.w + selectObj.csizeh && iMouseY > selectObj.y + selectObj.h - selectObj.csizeh && iMouseY < selectObj.y + selectObj.h + selectObj.csizeh) { canvas.css("cursor", "pointer"); selectObj.bHow[2] = true; selectObj.iCSize[2] = selectObj.csizeh; } if (iMouseX > selectObj.x - selectObj.csizeh && iMouseX < selectObj.x + selectObj.csizeh && iMouseY > selectObj.y + selectObj.h - selectObj.csizeh && iMouseY < selectObj.y + selectObj.h + selectObj.csizeh) { canvas.css("cursor", "pointer"); selectObj.bHow[3] = true; selectObj.iCSize[3] = selectObj.csizeh; } if (iMouseX > selectObj.x && iMouseX < selectObj.x + selectObj.w && iMouseY > selectObj.y && iMouseY < selectObj.y + selectObj.h) { canvas.css("cursor", "move"); } // in case of dragging of resize cubes var iFW, iFH, iFX, iFY, mx, my; if (selectObj.bDrag[0]) { iFX = iMouseX - selectObj.px; iFY = iMouseY - selectObj.py; iFW = selectObj.w + selectObj.x - iFX; iFH = selectObj.h + selectObj.y - iFY; canvas.data("drag", true); } if (selectObj.bDrag[1]) { iFX = selectObj.x; iFY = iMouseY - selectObj.py; iFW = iMouseX - selectObj.px - iFX; iFH = selectObj.h + selectObj.y - iFY; canvas.data("drag", true); } if (selectObj.bDrag[2]) { iFX = selectObj.x; iFY = selectObj.y; iFW = iMouseX - selectObj.px - iFX; iFH = iMouseY - selectObj.py - iFY; canvas.data("drag", true); } if (selectObj.bDrag[3]) { iFX = iMouseX - selectObj.px; iFY = selectObj.y; iFW = selectObj.w + selectObj.x - iFX; iFH = iMouseY - selectObj.py - iFY; canvas.data("drag", true); } if (iFW > selectObj.csizeh * 2 && iFH > selectObj.csizeh * 2) { selectObj.w = iFW; selectObj.h = iFH; selectObj.x = iFX; selectObj.y = iFY; } drawScene(); } function canvasMouseOut() { $(canvas).trigger("mouseup"); } function canvasMouseUp() { selectObj.bDragAll = false; for (var i = 0; i < 4; i++) { selectObj.bDrag[i] = false; } canvas.css("cursor", "default"); canvas.data("select", { x: selectObj.x, y: selectObj.y, w: selectObj.w, h: selectObj.h }); selectObj.px = 0; selectObj.py = 0; } function Selection(x, y, w, h) { this.x = x; // initial positions this.y = y; this.w = w; // and size this.h = h; this.px = x; // extra variables to dragging calculations this.py = y; this.csize = 4; // resize cubes size this.csizeh = 6; // resize cubes size (on hover) this.bHow = [false, false, false, false]; // hover statuses this.iCSize = [this.csize, this.csize, this.csize, this.csize]; // resize cubes sizes this.bDrag = [false, false, false, false]; // drag statuses this.bDragAll = false; // drag whole selection } Selection.prototype.draw = function () { ctx.strokeStyle = '#666'; ctx.lineWidth = 2; ctx.strokeRect(this.x, this.y, this.w, this.h); // draw part of original image if (this.w > 0 && this.h > 0) { ctx.drawImage(image, this.x, this.y, this.w, this.h, this.x, this.y, this.w, this.h); } // draw resize cubes ctx.fillStyle = '#999'; ctx.fillRect(this.x - this.iCSize[0], this.y - this.iCSize[0], this.iCSize[0] * 2, this.iCSize[0] * 2); ctx.fillRect(this.x + this.w - this.iCSize[1], this.y - this.iCSize[1], this.iCSize[1] * 2, this.iCSize[1] * 2); ctx.fillRect(this.x + this.w - this.iCSize[2], this.y + this.h - this.iCSize[2], this.iCSize[2] * 2, this.iCSize[2] * 2); ctx.fillRect(this.x - this.iCSize[3], this.y + this.h - this.iCSize[3], this.iCSize[3] * 2, this.iCSize[3] * 2); }; var drawScene = function () { ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); // clear canvas // draw source image ctx.drawImage(image, 0, 0, ctx.canvas.width, ctx.canvas.height); // and make it darker ctx.fillStyle = 'rgba(0, 0, 0, 0.5)'; ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height); // draw selection selectObj.draw(); canvas.mousedown(canvasMouseDown); canvas.on("touchstart", canvasMouseDown); }; var createSelection = function (x, y, width, height) { var content = $("#imagePreview"); x = x || Math.ceil((content.width() - width) / 2); y = y || Math.ceil((content.height() - height) / 2); return new Selection(x, y, width, height); }; var ctx = canvas[0].getContext("2d"); var iMouseX = 1; var iMouseY = 1; var image = new Image(); image.onload = function () { selectObj = createSelection(x, y, width, height); canvas.data("select", { x: selectObj.x, y: selectObj.y, w: selectObj.w, h: selectObj.h }); drawScene(); }; image.src = imageSource; canvas.mousemove(canvasMouseMove); canvas.on("touchmove", canvasMouseMove); var StopSelect = function (e) { var canvasOffset = $(canvas).offset(); var pageX = e.pageX || event.targetTouches[0].pageX; var pageY = e.pageY || event.targetTouches[0].pageY; iMouseX = Math.floor(pageX - canvasOffset.left); iMouseY = Math.floor(pageY - canvasOffset.top); selectObj.px = iMouseX - selectObj.x; selectObj.py = iMouseY - selectObj.y; if (selectObj.bHow[0]) { selectObj.px = iMouseX - selectObj.x; selectObj.py = iMouseY - selectObj.y; } if (selectObj.bHow[1]) { selectObj.px = iMouseX - selectObj.x - selectObj.w; selectObj.py = iMouseY - selectObj.y; } if (selectObj.bHow[2]) { selectObj.px = iMouseX - selectObj.x - selectObj.w; selectObj.py = iMouseY - selectObj.y - selectObj.h; } if (selectObj.bHow[3]) { selectObj.px = iMouseX - selectObj.x; selectObj.py = iMouseY - selectObj.y - selectObj.h; } if (iMouseX > selectObj.x + selectObj.csizeh && iMouseX < selectObj.x + selectObj.w - selectObj.csizeh && iMouseY > selectObj.y + selectObj.csizeh && iMouseY < selectObj.y + selectObj.h - selectObj.csizeh) { selectObj.bDragAll = true; } for (var i = 0; i < 4; i++) { if (selectObj.bHow[i]) { selectObj.bDrag[i] = true; } } }; canvas.mouseout(canvasMouseOut); canvas.mouseup(canvasMouseUp); canvas.on("touchend", canvasMouseUp); this.getImageData = function (previewID) { var tmpCanvas = $("<canvas></canvas>")[0]; var tmpCtx = tmpCanvas.getContext("2d"); if (tmpCanvas && selectObj) { tmpCanvas.width = selectObj.w; tmpCanvas.height = selectObj.h; tmpCtx.drawImage(image, selectObj.x, selectObj.y, selectObj.w, selectObj.h, 0, 0, selectObj.w, selectObj.h); if (document.getElementById(previewID)) { document.getElementById(previewID).src = tmpCanvas.toDataURL(); document.getElementById(previewID).style.border = "1px solid #ccc"; } return tmpCanvas.toDataURL(); } }; }

前端的有关IE兼容性的问题(图片的下载)

通过canvas画图, 然后生成图片,方式如下: var myc = document.getElementById("myCanvas"); var ctx=myc.getContext("2d"); var image = new Image(); ctx.clearRect(0,0,800,800);//清空一波画布 ctx.drawImage(一些参数);//画一张图片 image.src = myc.toDataURL("image/png");//生成这张图片,并将格式设定为png (生成这里貌似就出了问题,在火狐,谷歌之类的浏览器,进行了这一步之后是可以再图片上右击,然后进行图片的存储的,可是IE不行,IE的图片另存为那一栏是灰色的) 最后进行下载到本地, var _fixType = function(type) { type = type.toLowerCase().replace(/jpg/i, 'jpeg'); var r = type.match(/png|jpeg|bmp|gif/)[0]; return 'image/' + r; }; // 加工image data,替换mime type imgData = imgData.replace(_fixType(type),'image/octet-stream'); /** * 在本地进行文件保存 * @param {String} data 要保存到本地的图片数据 * @param {String} filename 文件名 */ var saveFile = function(data, filename){ var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a'); save_link.href = data; save_link.download = filename; var event = document.createEvent('MouseEvents'); event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); save_link.dispatchEvent(event); }; // 下载后的问题名 var filename = 'baidufe_' + (new Date()).getTime() + '.' + type; // download saveFile(imgData,filename); 然而这段代码就是在IE里面运行不了,火狐,谷歌之类都试过都可以正常运行,正常生成图片,并进行下载。 然后我在网上找了这么一段代码: var imgURL = img.src; var oPop = window.open(imgURL,"","width=1, height=1, top=5000, left=5000"); for(; oPop.document.readyState != "complete"; ) { if (oPop.document.readyState == "complete")break; } oPop.document.execCommand("SaveAs"); oPop.close(); 我发现当图片的路径地址URL确定的时候,就是说页面中的图片确实存在,且有真实路径的情况下是可以进行下载的(在IE下),但是在我用canvas画图画出来的图片再来进行存储的时候for(; oPop.document.readyState != "complete"; )这一行代码报错,报的错意思就是oPop不可为null之类的空值,原错是:无法获取未定义或 null 引用的属性“document”。 求各位大神帮忙看看吧,实在是没招儿了。

ie8下canvas.getContext()方法无效,求解决方案

canvas.getContext()是绘制一个绘画环境,目前只支持2d属性 网上也看过excanvas.js的方法,但是报错 //未知的运行时错误--excanvas.js 行144,字符9; el.innerHTML = ''; //意外地调用了方法或属性访问。--excanvas.js 行311,字符5; surfaceElement.appendChild(el);

#Leaflet#用Chart.js在JavaScript生成的canvas里面绘制饼图 获取ElementID后出错

一个基于Leaflet开发的小小小项目 问题大概只这样的: 首先是我用L.control()生成一个控件(info),通过.update()方法对控件进行更新。在.update()中我创建了一个新的canvas元素,之后通过document.getElementById()获取该元素,并使用Chart.js库创建一个饼图。在调用Chart.js库的时候就报错了(TypeError: item is null)。 ``` 相关资源: <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.js"></script> <style> #map{ height: 70% } .info { padding: 16px 10px; font: 14px/16px Arial, Helvetica, sans-serif; background: white; background: rgba(255,255,255,0.8); box-shadow: 0 0 15px rgba(0,0,0,0.2); border-radius: 5px; } .info h4 { margin: 0 0 5px; color: 'white'; } </style> ``` 报错内容如下: TypeError: item is nullChart.bundle.js:6904:14 acquireContext https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.js:6904 construct https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.js:8423 Chart https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.js:8410 update http://127.0.0.1:5500/static/js/load_tiff.js:85 onAdd http://127.0.0.1:5500/static/js/load_tiff.js:76 addTo http://127.0.0.1:5500/static/js/leaflet/leaflet.js:5 <anonymous> http://127.0.0.1:5500/static/js/load_tiff.js:90 ``` 相关代码如下: var randomScalingFactor = function() { return Math.round(Math.random() * 100); }; var config = { type: 'pie', data: { datasets: [{ data: [ randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), ], backgroundColor: [ "rgba(230, 14, 14, 1)", "rgba(230, 122, 14, 1)", "rgba(230, 230, 14, 1)", "rgba(122, 230, 14, 1)", "rgba(14, 122, 230, 1)", ], label: 'Dataset 1' }], labels: [ 'Red', 'Orange', 'Yellow', 'Green', 'Blue' ] }, options: { responsive: true } }; var info = L.control(); info.onAdd = function(mymap) { this._div = L.DomUtil.create('div', 'info'); this.update(); return this._div; }; info.update = function() { var content = '<h4>Statistic Info</h4>' + '<br />'; content += '<canvas id="myChart" width="10" height="10"></canvas>'; this._div.innerHTML = content; var piechart = new Chart(document.getElementById('myChart'),config) }; info.addTo(mymap); ```

将画布转换为img并仅打印图像

<div class="post-text" itemprop="text"> <p>Found solutions for opening html2canvas in new window and opening the print dialogue on window.open. However, the print dialogue presents as if I am printing a webpage, with whitespace around the image. I want to print nothing but the generated image. </p> <p>I'm not sure how to remove the whitespace. I'm hoping someone can steer me in the right direction.</p> <p>This is the code that generates the HTML:</p> <pre><code> &lt;?php $servername = "localhost"; $username = "xxxxxx"; $password = "xxxxx"; $dbname = "xxxxx"; $id = $_GET["id"]; try { $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); $conn-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $conn-&gt;prepare("SELECT Name, Number, PartA, PartB FROM Medicard WHERE `Medicard`.`id` = ?"); $stmt-&gt;execute(array($id)); // set the resulting array to associative $result = $stmt-&gt;setFetchMode(PDO::FETCH_ASSOC); foreach ($stmt-&gt;fetchAll() as $row) { echo "&lt;div id='html-content-holder' style='width: 3.375in; height: 2.125in; padding: 0;' &gt;"; echo '&lt;img style="width: 324px; height: 204px; margin-left: -2.5%; margin-top: -2%;" src="images/high-rez-medicare-card.jpg" alt="medicare card"/&gt;'; echo "&lt;div style='position: relative; width: 3.375in; height; 2.13in; margin-top: -2.125in;'&gt;&lt;/div&gt;"; echo "&lt;div style='width: 100%; padding: 73px 0 0 8px;' &gt;" . $row['Name'] . "&lt;/div&gt;"; echo "&lt;div style='width: 100%; margin: 30px auto auto 8px;' &gt;" . $row['Number'] . "&lt;/div&gt;"; echo "&lt;div style='width: 100%; margin: 11px auto auto 181px;' &gt;" . $row['PartA'] . "&lt;/div&gt;"; echo "&lt;div style='width: 100%; margin: 2px auto auto 181px;' &gt;" . $row['PartB'] . "&lt;/div&gt;"; echo "&lt;/div&gt;"; echo "&lt;/div&gt;"; echo "&lt;button id='printCard' onclick='print_card()'&gt;Print Image&lt;/button&gt;"; } } catch(PDOException $e) { echo "Error: " . $e-&gt;getMessage(); } $conn = null; ?&gt; </code></pre> <p>This is the html2canvas script:</p> <pre><code> &lt;script&gt; $(window).load(function () { var scaleBy = 3.12; var w = 324; var h = 204; var div = document.querySelector('#html-content-holder'); var canvas = document.createElement('canvas'); canvas.id = "canvas"; canvas.width = w * scaleBy; canvas.height = h * scaleBy; canvas.style.width = w + 'px'; canvas.style.height = h + 'px'; var context = canvas.getContext('2d'); context.scale(scaleBy, scaleBy); html2canvas(div, { canvas:canvas, onrendered: function (canvas) { theCanvas = canvas; document.body.appendChild(canvas); Canvas2Image.saveAsPNG(canvas); $(body).append(canvas); } }); }); &lt;/script&gt; </code></pre> <p>And finally this is the script that is designed to reload the image in a new window and open the print dialogue on button click:</p> <pre><code>&lt;script&gt; function print_card(){ var canvas=document.getElementById("canvas"); var win=window.open(); win.document.write("&lt;img src='"+canvas.toDataURL('image/png')+"' width:='324' height='204'/&gt;"); win.print(); win.location.reload(); } $("#printCard").click(function(){ print_card(); }); &lt;/script&gt; </code></pre> <p>For the most part this works as expected except that the resulting image is still surrounded by whitespace. I want it to be nothing but the image. Can anyone tell me what I am doing wrong?</p> <p>UPDATE: It appears as if the print dialogue is still trying to print the entire web page as opposed to just the image? How can I open a print dialogue that only contains the image.</p> <p>For instance, if I right click the image on the resulting page and click open in new tab, the new tab shows only the image. That is what I want to print.</p> <p>Thanks,</p> </div>

将Canvas映像保存到mysql

<div class="post-text" itemprop="text"> <p>Every 5 seconds I have my javascript running to call the update.php file (which will hopefully add the base64 code to the mysql - although yet to figure out).</p> <p>Currently, I just have the base64 code writing out to a text area called <strong>debugConsole</strong>.</p> <p>I just don't get how I'm supposed to pass the javascript variable to my php update file.</p> <p>HTML:</p> <pre><code>&lt;script type="text/javascript"&gt; function saveViaAJAX() { var testCanvas = document.getElementById("testCanvas"); var canvasData = testCanvas.toDataURL("image/png"); var postData = "canvasData="+canvasData; var debugConsole= document.getElementById("debugConsole"); debugConsole.value=canvasData; //alert("canvasData ="+canvasData ); var ajax = new XMLHttpRequest(); //ajax.open("POST",'testSave.php',true); ajax.setRequestHeader('Content-Type', 'canvas/upload'); //ajax.setRequestHeader('Content-TypeLength', postData.length); ajax.onreadystatechange=function() { if (ajax.readyState == 4) { //alert(ajax.responseText); // Write out the filename. document.getElementById("debugFilenameConsole").innerHTML="Saved as&lt;br&gt;&lt;a target='_blank' href='"+ajax.responseText+"'&gt;"+ajax.responseText+"&lt;/a&gt;&lt;br&gt;Reload this page to generate new image or click the filename to open the image file."; } } ajax.send(postData); } setInterval(function() { saveViaAJAX(); }, 5000); &lt;/script&gt; &lt;script language='javascript' type='text/javascript'&gt; //Every 5 seconds calls php update //syncronized jax: function myjax() { oXhr = new XMLHttpRequest(); oXhr.open("POST", "update.php?game=&lt;?php echo $game; ?&gt;", false); oXhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8"); oXhr.send(null); } //set an interval each 5 seconds to call your myjax method setInterval(function() { myjax(); }, 5000); &lt;/script&gt; &lt;/head&gt; &lt;div&gt; &lt;canvas id="testCanvas" width="300" height="300"&gt;&lt;/canvas&gt; &lt;/div&gt; &lt;div&gt; &lt;textarea id="debugConsole" rows="10" cols="60"&gt;Data&lt;/textarea&gt; &lt;/div&gt; &lt;script type="text/javascript"&gt; // This portion of the code simply draws random circles into the canvas (it has nothing todo with saving the canvas). var canvas = document.getElementById("testCanvas"); if (canvas.getContext) { var canvasContext = canvas.getContext("2d"); for (i=0; i&lt;150; i++) { canvasContext.fillStyle="rgb("+(parseInt(Math.random()*255))+","+(parseInt(Math.random()*255))+","+(parseInt(Math.random()*255))+")"; canvasContext.beginPath(); canvasContext.arc(Math.random()*350,Math.random()*350,Math.random()*20, 0,Math.PI*2,true); canvasContext.fill(); } } &lt;/script&gt; </code></pre> <p>PHP:</p> <pre><code>&lt;?php $random = rand(); $game = $_GET["game"]; mysql_query("UPDATE paint_s SET paint_points='$random' WHERE id ='$game'") or die(mysql_error()); echo "Updated"; ?&gt; </code></pre> <p>Sorry for my lack of knowledge, I have been doing a few tutorials and was just trying to expand on the tutorial.</p> </div>

HTML - 使用Javascript / canvas和HTML将上传的图像拉入PHP

<div class="post-text" itemprop="text"> <p><strong>Please see below for the answer to my own question</strong></p> <p>I hope you can help. </p> <p>I have been working on a HTML form which as an image, which is automatically re-sized when uploaded, by pre-defined parameters. I have listed the example code I have within this form at the moment. I don't think that the problem I am having is with the HTML code posted below, as on the HTML page everything works as expected, it is only when the PHP is invoked things don't go to plan. </p> <p>HTML code:</p> <pre><code> &lt;input id="width" type="hidden" value="320" /&gt; &lt;input id="height" type="hidden" /&gt; &lt;input id="file" type="file" capture="camera"/&gt; &lt;br /&gt;&lt;span id="message"&gt;&lt;/span&gt;&lt;br /&gt; &lt;div id="img"&gt;&lt;/div&gt; </code></pre> <p>Script directly beneath HTML code: </p> <pre><code>(function (global, $width, $height, $file, $message, $img) { // simple FileReader detection if (!global.FileReader) return $message.innerHTML = "FileReader API not supported" ; // async callback, received the base 64 encoded resampled image function resampled(data) { $message.innerHTML = "Image Preview:"; ($img.lastChild || $img.appendChild(new Image) ).src = data; } // async callback, fired when the image file has been loaded function load(e) { $message.innerHTML = "resampling ..."; //resample.js Resample( this.result, this._width || null, this._height || null, resampled ); } // async callback, fired if the operation is aborted function abort(e) { $message.innerHTML = "operation aborted"; } // async callback, fired if an error occur (i.e. security) function error(e) { $message.innerHTML = "Error: " + (this.result || e); } // listener for the input@file onchange $file.addEventListener("change", function change() { var width = parseInt($width.value, 10), height = parseInt($height.value, 10), file ; // no width and height specified if (!width &amp;&amp; !height) { // reset the input simply swapping it $file.parentNode.replaceChild( file = $file.cloneNode(false), $file ); // remove the listener to avoid leaks, if any $file.removeEventListener("change", change, false); // reassign the $file DOM pointer with the new input text and add the change listener ($file = file).addEventListener("change", change, false); // notify user there was something wrong $message.innerHTML = "please specify width or height"; } else if( // there is a files property and this has a length greater than 0 ($file.files || []).length &amp;&amp; /^image\//.test((file = $file.files[0]).type) ) { // reading action notification $message.innerHTML = "reading ..."; // create a new object file = new FileReader; // assign directly events as example, Chrome does not inherit EventTarget yet so addEventListener won't work as expected file.onload = load; file.onabort = abort; file.onerror = error; // cheap and easy place to store desired width and/or height file._width = width; file._height = height; // time to read as base 64 encoded data te selected image file.readAsDataURL($file.files[0]); // it will notify onload when finished } else if (file) { // if file variable has been created during precedent checks, there is a file but the type is not the expected one wrong file type notification $message.innerHTML = "please chose an image";} else { // No File Attached! $message.innerHTML = "No File Attached!"; } }, false); }( // the global object this, // all required fields ... document.getElementById("width"), document.getElementById("height"), document.getElementById("file"), document.getElementById("message"), document.getElementById("img") )); </code></pre> <p></p> <p>Actual Javascript code:</p> <pre><code>var Resample = (function (canvas) { // Resample function, accepts an image // as url, base64 string, or Image/HTMLImgElement // optional width or height, and a callback // to invoke on operation complete function Resample(img, width, height, onresample) { var // check the image type load = typeof img == "string", // Image pointer i = load || img ; // if string, a new Image is needed if (load) { i = new Image; // with propers callbacks i.onload = onload; i.onerror = onerror; } // easy/cheap way to store info i._onresample = onresample; i._width = width; i._height = height; // if string, we trust the onload event // otherwise we call onload directly // with the image as callback context load ? (i.src = img) : onload.call(img); } // just in case something goes wrong function onerror() { throw ("not found: " + this.src); } // called when the Image is ready function onload() { var // minifier friendly img = this, // the desired width, if any width = img._width, // the desired height, if any height = img._height, // the callback onresample = img._onresample ; // if width and height are both specified // the resample uses these pixels // if width is specified but not the height // the resample respects proportions // accordingly with orginal size // same is if there is a height, but no width width == null &amp;&amp; (width = round(img.width * height / img.height)); height == null &amp;&amp; (height = round(img.height * width / img.width)); // remove (hopefully) stored info delete img._onresample; delete img._width; delete img._height; // when we reassign a canvas size // this clears automatically // the size should be exactly the same // of the final image // so that toDataURL ctx method // will return the whole canvas as png // without empty spaces or lines canvas.width = width; canvas.height = height; // drawImage has different overloads // in this case we need the following one ... context.drawImage( // original image img, // starting x point 0, // starting y point 0, // image width img.width, // image height img.height, // destination x point 0, // destination y point 0, // destination width width, // destination height height ); // retrieve the canvas content as // base4 encoded PNG image // and pass the result to the callback onresample(canvas.toDataURL("image/png")); } var // point one, use every time ... context = canvas.getContext("2d"), // local scope shortcut round = Math.round ; return Resample; }( // lucky us we don't even need to append // and render anything on the screen // let's keep this DOM node in RAM // for all resizes we want this.document.createElement("canvas")) ); </code></pre> <p>I'm happy with the above scripts, they could do with being slimmed down a little, but performance isn't key at the moment, only functionality. Now it may seem daft, but I do not know where to even begin with PHP to get this posting, I do have a PHP file, which is used to print fields from the HTML, as an example I have the following code for some other fields present in the form:</p> <pre><code>if($_SERVER['REQUEST_METHOD']=='POST') { $address = test_input($_POST['address1']); $address2 = test_input($_POST['address2']); $address3 = test_input($_POST['address3']); $cover = test_input($_POST['coverphoto']); $consultantName = test_input($_POST['consultantName']); $reportDate = test_input($_POST['reportDate']); $reportDate = date_create($reportDate); </code></pre> <p>Would you be able to let me know the best way to get the above HTML code to post the image through to PHP? My previous attempts have left with just a blank space, as if no code was there in the first place. I have done some extensive research around this in the past couple of day, but just can't get my head around it! </p> <p>Many thanks in advance. </p> </div>

js中定义的函数在button中的onclick调用时显示函数未定义

<!doctype html> <html> <head> <meta charset="utf-8"> <title>螺旋图案</title> <script type="text/javascript"> var canvas=document.getElementById("canvas"); var context=canvas.getContext("2d"); var A,n; btn_onclick=function(){ var width=canvas.width; var height=canvas.height; var X0=width/2; var Y0=height/2; var k=parseInt(document.getElementById("drawType").value); if(k==2) A=Y0*0.25; else A=Y0*0.75; context.save(); context.clearRect(0,0,width,height); context.translate(X0,Y0); context.beginPath(); for(var B=0;B<=6.28;B=B+0.01) draw(B); context.closePath(); context.restore(); } draw=function(B){ var n=10; switch(parseInt(document.getElementById("drawType").value)){ case 1: r=A*Math.sin(n*B); break; case 2: r=A*(Math.sin(n*B)+3*Math.sin(3*n*B)); } x=r*Math.cos(B); y=r*Math.sin(B); context.fillStyle="green"; context.strokeStyle="black"; context.lineTo(-x,-y); context.fill(); context.stroke(); } </script> </head> <body> <select id="drawType"> <option value="1">蓬莱菊花</option> <option value="2">令箭荷花</option> </select> <canvas id="canvas" width="200px" height="200px"></canvas> <input type="button" id="btn" value="绘制" onClick="btn_onclick();"/> </body> </html>

怎么把js函数的参数变成全局变量,用到后面的函数中运算

通过函数计算得到gwp的数值,如果转化成全局变量值,用到后面的绘图函数中 ``` var gwp1=[]; $(function(){ var dom = document.getElementById("box4"); var myChart = echarts.init(dom); var app = {}; option = null; var y_f = []; //全局变量,wgid在gognweizongtu.js中获取 var gwp = 0; var xishu = [0.4,0.2,0.3,0.1]; var pjx = ["gzp","gyp","wlp","ryp"]; var pj = {"gongzhuang":"OK", "gongyi": "OK", "wuliao": "OK", "renyuan": "OK"}; var guige = [90, 90, 80, 75,85]; var xiang = ["gongzhuang","gongyi","wuliao","renyuan"]; for (var i = 0 ; i< xiang.length ; i++) { var lent = data[xiang[i]].y.length ; var ind = lent - 1 ; y_f.push(data[xiang[i]].y[ind]); if (data[xiang[i]].y[ind] < guige[i]){ pj[xiang[i]] = "NOK"; } document.getElementById(pjx[i]).innerHTML = pj[xiang[i]]; gwp += y_f[i]*xishu[i]; } y_f.push(88); if (gwp > 85.5){ document.getElementById("gwpj").innerHTML ="OK"; } gwp = gwp.toFixed(2); /*绘图代码省略*/ }; if (option && typeof option === "object") { myChart.setOption(option, true); } }) ``` 上部分代码得到gwp的数值,如何用到后面的画圆代码 darwPro("myCanvas",gwp/100);,画圆时老是提示gwp值为空 ``` <!-- 圆弧绘制--> //画圆方法 function drawArc(canvas,begin,end,color) { canvas.beginPath(); canvas.lineWidth = 6; canvas.fillStyle = "#ffffff"; canvas.strokeStyle = color; canvas.arc(48, 48, 40, begin,end); canvas.fill(); canvas.stroke(); canvas.closePath(); } //添加文字方法 function drawWord(canvas,text){ canvas.font = 'bold 20px arial'; canvas.fillStyle = 'red'; canvas.fillText(text, 30,53); } //每100毫秒画一次,300毫秒完成 function darwPro(id,rate){ //获取画布对象 var canvasID = document.getElementById("myCanvas"); var canvas = canvasID.getContext("2d"); window.alert(rate); //先画背景 drawArc(canvas,-0.5*Math.PI,1.5*Math.PI,"#EDEDED"); //setInterval()函数至少执行一次(当rate为零时直接返回) if(rate == 0){ return; } //为了体现动态图使用分段画图的策略 var begin = -0.5*Math.PI;//起始角度 var end = 2*Math.PI*rate-0.5*Math.PI;//结束角度 var add = 2*Math.PI*rate/10;//分段的增量 //分10次完成每次间隔50毫秒 var sid = setInterval(function(){ if(begin >= end){ clearInterval(sid); return;//此处必须return;因为即使clearInterval,函数仍然会执行一次导致比例不准确 } drawArc(canvas,begin, begin + add,"green"); //下次起始位置置为上次结束的位置 begin = begin + add; }, 50); //显示百分比的文字 drawWord(canvas,rate*100 + "%"); } darwPro("myCanvas",gwp/100); ```

关于ajax传值失败的问题

这是前端代码 ``` <body> <div class="booth"> <video id="video" width="400" height="300"></video> <input id='tack' type="button" value="拍照"> <canvas id='canvas' width='400' height='300'></canvas> <img id='img' src=''> <input type="button" onclick="uploadImage();" value="上传"> </div> <script> var video = document.getElementById('video'), canvas = document.getElementById('canvas'), snap = document.getElementById('tack'), img = document.getElementById('img'), vendorUrl = window.URL || window.webkitURL; //媒体对象 navigator.getMedia = navigator.getUserMedia || navagator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia; navigator.getMedia({ video: true, //使用摄像头对象 audio: false //不适用音频 }, function(strem){ console.log(strem); video.src = vendorUrl.createObjectURL(strem); video.play(); }, function(error) { //error.code console.log(error); }); snap.addEventListener('click', function(){ //绘制canvas图形 canvas.getContext('2d').drawImage(video, 0, 0, 400, 300); //把canvas图像转为img图片 img = canvas.toDataURL("image/png"); }); function uploadImage(){ $.ajax({ type:'post', url:'UploadImage', data:{image:img}, async:false, datatype:'json', success:function(data){ if(data.success){ alret('上传成功'); }else{ alret('上传失败'); } }, error:function(err){ alert('网络故障'); } }); } ``` 这是后台代码 ![图片说明](https://img-ask.csdn.net/upload/201806/06/1528275434_398160.png) 我想用ajax把“img=canvas.toDataURL("image/png")”的数据传回后台UploadImage,可是后台打印出来的一直是null,想请问代码应该怎么修改? 如果用<from>来传,<input>应该怎么写

百度API 为什么报这个错啊 大神们有谁能来看看 再次谢谢 ......

老铁们 大神们,,我这里这个怎么抢救啊 我调了 百度的API 然后想拿到这个识别 结果 我是前台浏览器JS 脚本拍的图片 BASE 64 转码到后台 放到百度去识别 我确信 我拍的是我自己图片 结果每次 pic ``` String url = "https://aip.baidubce.com/rest/2.0/face/v3/search"; //请求的url,可以查看官方文档查看不同请求的url // String flag = request.getParameter("flag"); Map<String, Object> map = new HashMap<>(); map.put("image", request.getParameter("base"));//获取前台的人脸识别后发送的base64 map.put("group_id_list", "itcast");//之前创建的人脸库,可以在百度云的管理控制台查看用户组,face1是之前命名好的 map.put("image_type", "BASE64");//照片类型为base64 // map.put("quality_control", "NORMAL"); String param = GsonUtils.toJson(map); // 注意这里仅为了简化编码每一次请求都去获取access_token,线上环境access_token有过期时间, 客户端可自行缓存,过期后重新获取。 String accessToken = GetToken.getAuth(); String result = null; try { result = HttpUtil.post(url, accessToken, "application/json", param); } catch (Exception e) { e.printStackTrace(); } System.out.println("识别结果为:"+result); ``` 前台代码 ``` function takePhoto() { //获得Canvas对象 var video = document.getElementById('video'); var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); // ctx.drawImage(video, 0, 0, 500, 500); // toDataURL --- 可传入'image/png'---默认, 'image/jpeg' var img = document.getElementById('canvas').toDataURL("image/png"); var base = img.split("base64,")[1]; // alert(base); console.log(base); // 这里的img就是得到的图片 // console.log('img-----', img); /* * 发送这个数据 * */ $.ajax({ type:"post", url:"testServlet", data:{ "base":base, "flag":"queryfacekey" }, dataType: "json", success:function(json){ location.href = "index.html"; // if("登录成功"==json.mess){ // window.parent.location.replace("<%=path%>/main.jsp"); // }else{ // $.MsgBox.Alert("消息",json.mess); // location.href = "login.html"; }, error:function(){ alert("error"); } }); // document.getElementById('imgTag').src=img; } // 关闭摄像头 function closeMedia() { mediaStreamTrack.stop(); } ``` 为啥报这个错result:{"error_code":222202,"error_msg":"pic not has face","log_id":8494947994101,"timestamp":1588490657,"cached":0,"result":null}

4小时玩转微信小程序——基础入门与微信支付实战

4小时玩转微信小程序——基础入门与微信支付实战

Python可以这样学(第四季:数据分析与科学计算可视化)

Python可以这样学(第四季:数据分析与科学计算可视化)

组成原理课程设计(实现机器数的真值还原等功能)

实现机器数的真值还原(定点小数)、定点小数的单符号位补码加减运算、定点小数的补码乘法运算和浮点数的加减运算。

javaWeb图书馆管理系统源码mysql版本

系统介绍 图书馆管理系统主要的目的是实现图书馆的信息化管理。图书馆的主要业务就是新书的借阅和归还,因此系统最核心的功能便是实现图书的借阅和归还。此外,还需要提供图书的信息查询、读者图书借阅情况的查询等

土豆浏览器

土豆浏览器可以用来看各种搞笑、电影、电视剧视频

Java面试题大全(2020版)

发现网上很多Java面试题都没有答案,所以花了很长时间搜集整理出来了这套Java面试题大全,希望对大家有帮助哈~ 本套Java面试题大全,全的不能再全,哈哈~ 一、Java 基础 1. JDK 和 JRE 有什么区别? JDK:Java Development Kit 的简称,java 开发工具包,提供了 java 的开发环境和运行环境。 JRE:Java Runtime Environ...

Java8零基础入门视频教程

Java8零基础入门视频教程

Java基础知识面试题(2020最新版)

文章目录Java概述何为编程什么是Javajdk1.5之后的三大版本JVM、JRE和JDK的关系什么是跨平台性?原理是什么Java语言有哪些特点什么是字节码?采用字节码的最大好处是什么什么是Java程序的主类?应用程序和小程序的主类有何不同?Java应用程序与小程序之间有那些差别?Java和C++的区别Oracle JDK 和 OpenJDK 的对比基础语法数据类型Java有哪些数据类型switc...

TTP229触摸代码以及触摸返回值处理

自己总结的ttp229触摸代码,触摸代码以及触摸按键处理

网络工程师小白入门--【思科CCNA、华为HCNA等网络工程师认证】

网络工程师小白入门--【思科CCNA、华为HCNA等网络工程师认证】

深度学习原理+项目实战+算法详解+主流框架(套餐)

深度学习系列课程从深度学习基础知识点开始讲解一步步进入神经网络的世界再到卷积和递归神经网络,详解各大经典网络架构。实战部分选择当下最火爆深度学习框架PyTorch与Tensorflow/Keras,全程实战演示框架核心使用与建模方法。项目实战部分选择计算机视觉与自然语言处理领域经典项目,从零开始详解算法原理,debug模式逐行代码解读。适合准备就业和转行的同学们加入学习! 建议按照下列课程顺序来进行学习 (1)掌握深度学习必备经典网络架构 (2)深度框架实战方法 (3)计算机视觉与自然语言处理项目实战。(按照课程排列顺序即可)

java jdk 8 帮助文档 中文 文档 chm 谷歌翻译

JDK1.8 API 中文谷歌翻译版 java帮助文档 JDK API java 帮助文档 谷歌翻译 JDK1.8 API 中文 谷歌翻译版 java帮助文档 Java最新帮助文档 本帮助文档是使用谷

Ubuntu18.04安装教程

Ubuntu18.04.1安装一、准备工作1.下载Ubuntu18.04.1 LTS2.制作U盘启动盘3.准备 Ubuntu18.04.1 的硬盘空间二、安装Ubuntu18.04.1三、安装后的一些工作1.安装输入法2.更换软件源四、双系统如何卸载Ubuntu18.04.1新的改变功能快捷键合理的创建标题,有助于目录的生成如何改变文本的样式插入链接与图片如何插入一段漂亮的代码片生成一个适合你的列...

快速排序---(面试碰到过好几次)

原理:    快速排序,说白了就是给基准数据找其正确索引位置的过程.    如下图所示,假设最开始的基准数据为数组第一个元素23,则首先用一个临时变量去存储基准数据,即tmp=23;然后分别从数组的两端扫描数组,设两个指示标志:low指向起始位置,high指向末尾.    首先从后半部分开始,如果扫描到的值大于基准数据就让high减1,如果发现有元素比该基准数据的值小(如上图中18&amp;lt...

手把手实现Java图书管理系统(附源码)

手把手实现Java图书管理系统(附源码)

HTML期末大作业

这是我自己做的HTML期末大作业,花了很多时间,稍加修改就可以作为自己的作业了,而且也可以作为学习参考

Python数据挖掘简易入门

Python数据挖掘简易入门

极简JAVA学习营第四期(报名以后加助教微信:eduxy-1)

极简JAVA学习营第四期(报名以后加助教微信:eduxy-1)

C++语言基础视频教程

C++语言基础视频教程

UnityLicence

UnityLicence

软件测试2小时入门

软件测试2小时入门

YOLOv3目标检测实战:训练自己的数据集

YOLOv3目标检测实战:训练自己的数据集

Python数据分析师-实战系列

系列课程主要包括Python数据分析必备工具包,数据分析案例实战,核心算法实战与企业级数据分析与建模解决方案实战,建议大家按照系列课程阶段顺序进行学习。所有数据集均为企业收集的真实数据集,整体风格以实战为导向,通俗讲解Python数据分析核心技巧与实战解决方案。

YOLOv3目标检测实战系列课程

《YOLOv3目标检测实战系列课程》旨在帮助大家掌握YOLOv3目标检测的训练、原理、源码与网络模型改进方法。 本课程的YOLOv3使用原作darknet(c语言编写),在Ubuntu系统上做项目演示。 本系列课程包括三门课: (1)《YOLOv3目标检测实战:训练自己的数据集》 包括:安装darknet、给自己的数据集打标签、整理自己的数据集、修改配置文件、训练自己的数据集、测试训练出的网络模型、性能统计(mAP计算和画出PR曲线)和先验框聚类。 (2)《YOLOv3目标检测:原理与源码解析》讲解YOLOv1、YOLOv2、YOLOv3的原理、程序流程并解析各层的源码。 (3)《YOLOv3目标检测:网络模型改进方法》讲解YOLOv3的改进方法,包括改进1:不显示指定类别目标的方法 (增加功能) ;改进2:合并BN层到卷积层 (加快推理速度) ; 改进3:使用GIoU指标和损失函数 (提高检测精度) ;改进4:tiny YOLOv3 (简化网络模型)并介绍 AlexeyAB/darknet项目。

超详细MySQL安装及基本使用教程

一、下载MySQL 首先,去数据库的官网http://www.mysql.com下载MySQL。 点击进入后的首页如下:  然后点击downloads,community,选择MySQL Community Server。如下图:  滑到下面,找到Recommended Download,然后点击go to download page。如下图:  点击download进入下载页面选择No...

一学即懂的计算机视觉(第一季)

一学即懂的计算机视觉(第一季)

董付国老师Python全栈学习优惠套餐

购买套餐的朋友可以关注微信公众号“Python小屋”,上传付款截图,然后领取董老师任意图书1本。

爬取妹子图片(简单入门)

安装第三方请求库 requests 被网站禁止了访问 原因是我们是Python过来的 重新给一段 可能还是存在用不了,使用网页的 编写代码 上面注意看匹配内容 User-Agent:请求对象 AppleWebKit:请求内核 Chrome浏览器 //请求网页 import requests import re //正则表达式 就是去不规则的网页里面提取有规律的信息 headers = { 'User-Agent':'存放浏览器里面的' } response = requests.get

web网页制作期末大作业

分享思维,改变世界. web网页制作,期末大作业. 所用技术:html css javascript 分享所学所得

技术大佬:我去,你写的 switch 语句也太老土了吧

昨天早上通过远程的方式 review 了两名新来同事的代码,大部分代码都写得很漂亮,严谨的同时注释也很到位,这令我非常满意。但当我看到他们当中有一个人写的 switch 语句时,还是忍不住破口大骂:“我擦,小王,你丫写的 switch 语句也太老土了吧!” 来看看小王写的代码吧,看完不要骂我装逼啊。 private static String createPlayer(PlayerTypes p...

相关热词 c#跨线程停止timer c#批量写入sql数据库 c# 自动安装浏览器 c#语言基础考试题 c# 偏移量打印是什么 c# 绘制曲线图 c#框体中的退出函数 c# 按钮透明背景 c# idl 混编出错 c#在位置0处没有任何行
立即提问