素材牛VIP会员
canvas 清除画面的问题
 贝***0  分类:JavaScript  人气:933  回帖:2  发布于6年前 收藏

用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>

下图上面三条线是上次画的,第四条是当前画的,如果松开鼠标画面就会清空,但要再画的时候,上次画过的线又会出现在画布上,我想做的是每次画都是从零开始

 标签:html5javascript

讨论这个帖子(2)垃圾回帖将一律封号处理……

Lv5 码农
15***75 技术总监 6年前#1

window.location.href = window.location.href;
反正都要清空画布了,直接刷新一波界面

Lv2 入门
雷***习 技术总监 6年前#2
   canvas.onmousedown=function(e){
       ctx.beginPath();//加上这一句就可以了。
       ctx.moveTo(e.clientX,e.clientY);
 文明上网,理性发言!   😉 阿里云幸运券,戳我领取