鍍金池/ 問答/HTML5  HTML/ canvas 清除畫面的問題

canvas 清除畫面的問題

用canvas做一個鼠標(biāo)畫線的demo,每次畫完后鼠標(biāo)UP的時候,清空一下畫布,然后下次畫的時候是從零開始的,現(xiàn)在問題是,鼠標(biāo)UP的時候清空是清空了,但再次畫的時候,上次畫過的線還會出現(xiàn)在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>

下圖上面三條線是上次畫的,第四條是當(dāng)前畫的,如果松開鼠標(biāo)畫面就會清空,但要再畫的時候,上次畫過的線又會出現(xiàn)在畫布上,我想做的是每次畫都是從零開始

圖片描述

回答
編輯回答
寫榮

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

2018年7月26日 06:04
編輯回答
笑浮塵
   canvas.onmousedown=function(e){
       ctx.beginPath();//加上這一句就可以了。
       ctx.moveTo(e.clientX,e.clientY);
2017年2月26日 06:55