删除画布上的前几行

时间:2018-12-12 18:09:08

标签: javascript html canvas

我正在尝试使用画布创建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>

2 个答案:

答案 0 :(得分:1)

每次绘制时都需要擦除画布。最好将HTML5画布视为一次绘制一帧。因此,绘制下一帧时,应使用clearRect()清除上一帧:

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

CodePen:https://codepen.io/chiss22/pen/wRKJON

答案 1 :(得分:0)

最简单,最常见的解决方案是清除整个画布,并在每个步骤重新绘制时钟。

setInterval(function () {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    drawClock();
}, 1000);

其他说明:

  • 在开始填充文本之前,只需设置一次字体
  • 您应该将drawFace,drawFont,drawHands和getTime从drawClock函数中移出,以免每次都重新创建它们。
相关问题