在Canvas中添加save()和restore()方法是因为Canvas的绘制实在上一个绘制图形之后继续绘制的(覆盖)。
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style> body{ background: red; } #canvas{ background: white; width: 400px; height: 400px; } </style> </head> <body> <!-- 默认canvas大小width300px,height150px --> <!-- 宽高必须在canvas标签的属性中设置,在css中写的话,是将canvas进行拉伸 --> <canvas id="canvas" width="400" height="400"> <span>这是一个画布,请用ie10+浏览器查看,或者。。。。</span> </canvas> <input type="color" id="colorInput"/> <input type="number" id="numberInput" value="1"/> <script> //得到画布 var oC = document.getElementById('canvas'); //得到canvas的上下文环境 //目前只支持2d环境 var oGC = oC.getContext('2d'); oC.onmousedown = function(ev){ var colorInput = document.getElementById('colorInput'); var numberInput = document.getElementById('numberInput'); oGC.strokeStyle = colorInput.value; oGC.lineWidth = numberInput.value; oGC.beginPath(); var ev = ev || window.event; //得到按下这个点相对于canvas的位置 oGC.moveTo(ev.clientX - oC.offsetLeft, ev.clientY - oC.offsetTop); document.onmousemove = function(ev){ var ev = ev || window.event; oGC.lineTo(ev.clientX - oC.offsetLeft, ev.clientY - oC.offsetTop); oGC.stroke(); } document.onmouseup = function(){ oGC.closePath(); document.onmousemove = null; document.onmouseup = null; } } </script> </body> </html>
转载于:https://www.cnblogs.com/wmwPro/p/5642888.html
相关资源:微信小程序 canvas API详解及实例代码