<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body style="background: black;">
<canvas id="c1" width="300px" height="300px" style="background-color: #fff;"></canvas>
<br /><input type="button" name="" id="inp" value="清空" />
<script type="text/javascript">
var oC1=document.getElementById("c1");
var oInp=document.getElementsByTagName("input")[0];
var oGC=oC1.getContext("2d");
oGC.fillStyle="#FF0000";
oGC.strokeStyle="#000";
oC1.onmousedown=function(ev){
oGC.clearRect(0,0,oC1.width,oC1.height);
var ev=ev||event;
oGC.moveTo(ev.clientX-oC1.offsetLeft,ev.clientY-oC1.offsetTop);
document.onmousemove=function(ev){
var ev=ev||event;
oGC.lineTo(ev.clientX-oC1.offsetLeft,ev.clientY-oC1.offsetTop);
oGC.stroke();
}
document.onmouseup=function () {
document.onmousemove=null;
}
}
oInp.onclick=function () {
oGC.clearRect(0,0,oC1.width,oC1.height);
}
</script>
</body>
</html>
点击按钮后清除画布,再一次画图,之前的图像又跑出来了,求解决
在
oGC.moveTo
前先oGC.beginPath()
。不然你的
moveTo
和lineTo
会一直留在默认 path 里。