用canvas做一个鼠标画线的demo,每次画完后鼠标UP的时候,清空一下画布,然后下次画的时候是从零开始的,现在问题是,鼠标UP的时候清空是清空了,但再次画的时候,上次画过的线还会出现在canvas上,为什么呢?
源码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>canvas</title>
<style lang="">
*{
margin: 0;
padding: 0;
}
#canvas{
border: 1px solid #333;
}
</style>
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<script>
var canvas=document.querySelector('canvas');
var ctx=canvas.getContext('2d');
canvas.onmousedown=function(e){
ctx.moveTo(e.clientX,e.clientY)
document.onmousemove=function(e){
ctx.lineTo(e.clientX,e.clientY)
ctx.stroke()
}
document.onmouseup=function(){
console.log(1)
document.onmousemove=null;
document.onmouseup=null;
ctx.clearRect(0,0,canvas.width,canvas.height)
}
}
</script>
</body>
</html>
下图上面三条线是上次画的,第四条是当前画的,如果松开鼠标画面就会清空,但要再画的时候,上次画过的线又会出现在画布上,我想做的是每次画都是从零开始