首页 > 解决方案 > 擦除前几行画布

问题描述

我正在尝试使用画布创建一个 JavaScript 时钟,除了绘制新行时前面的行不会消失之外,我已经打开了所有内容到目前为止,我想擦除画布中以前绘制的线条,它会一个接一个地创建新的线条。谢谢

var canvas = document.getElementById("mycanvas");
var ctx = canvas.getContext("2d");
var radius = canvas.height / 2;
ctx.translate(radius, radius)
radius = radius * 0.90

setInterval(drawClock, 1000);





function drawClock() {
     drawFace(ctx, radius);
        function drawFace(ctx, radius) {        
            ctx.beginPath();
            ctx.arc(0, 0,8, 0, 2*Math.PI);
            ctx.fillStyle = '#000000';
            ctx.fill();            
        }
        function drawFont(){
            ctx.font = "30px Arial";
            ctx.fillText("12",-17,-140);
            ctx.font = "30px Arial ";
            ctx.fillText("3",140,10);
            ctx.font = "30px Arial";
            ctx.fillText("6",-17,160);
            ctx.font = "30px Arial";
            ctx.fillText("9",-160,10);
            drawFace();

         }
        function drawHands(length, width, color,ang){            
            ctx.save();
            let deg= Math.PI/180;
            ctx.rotate(ang);
            ctx.moveTo(0,0);
            ctx.strokeStyle = color;
            ctx.lineWidth = width;
            ctx.lineTo(0,length);
            ctx.lineCap = 'round'; 
            ctx.stroke();
            ctx.restore();
            drawFont();   


        } 
        function getTime(){
            var now = new Date();
            var hour = now.getHours(); 
            var minute = now.getMinutes();
            var second = now.getSeconds();
            // console.log( hour+'::'+ minute + ': '+ second)

            var hours = (hour*Math.PI/6)+
                (minute*Math.PI/(6*60))+
                (second*Math.PI/(360*60));
            var minutes =   minute=(minute*Math.PI/30)+(second*Math.PI/(30*60));
            let seconds=(second*Math.PI/30);


                // drawHands(-90, 5, 'blue', hours);  
                // drawHands(-120, 4, 'red', minutes);    
                drawHands(-150, 2, 'black', seconds);


            console.log(seconds)

            ctx.putImageData(imageData, 0, 0);

        }

        getTime();
}

我的 html

<canvas id="mycanvas" width="350px" height="350px"
                        style="border:8px inset gray; border-radius: 190px;  margin: auto;">

                        </canvas>

标签: javascripthtmlcanvas

解决方案


每次绘制时都需要擦除画布。最好将 HTML5 Canvas 视为一次绘制一帧。因此,当您绘制下一帧时,您应该使用以下命令清除前一帧clearRect()

ctx.clearRect(-canvas.width/2, -canvas.height/2, canvas.width, canvas.height); // x, y, w, h

代码笔: https ://codepen.io/chiss22/pen/wRKJON


推荐阅读