擦除 HTML5 画布上先前绘制的线条

2022-01-17 00:00:00 javascript html html5-canvas

为了玩转 HTML5 画布,我决定制作一个绘制模拟表盘的应用程序.一切都很好,只是旧行没有像我期望的那样被删除.我在下面包含了部分代码 - DrawHands() 每秒调用一次:

To play around with HTML5 canvas, I decided to make an app which draws an analogue clockface. Everything's fine, except that old lines don't get erased in the way that I would expect. I've included part of the code below - DrawHands() gets called once a second:

var hoursPoint = new Object();
var minutesPoint = new Object();
var secondsPoint = new Object();

function drawHands()
{
    var now = new Date();

    drawLine(centerX, centerY, secondsPoint.X, secondsPoint.Y, "white", 1);
    var seconds = now.getSeconds();
    secondsPoint = getOtherEndOfLine(centerX, centerY, 2 * Math.PI / 60 * seconds, 0.75 * radius);
    drawLine(centerX, centerY, secondsPoint.X, secondsPoint.Y, "black", 1);

    drawLine(centerX, centerY, minutesPoint.X, minutesPoint.Y, "white", 3);
    var minutes = now.getMinutes();
    minutesPoint = getOtherEndOfLine(centerX, centerY, 2 * Math.PI / 60 * minutes, 0.75 * radius);
    drawLine(centerX, centerY, minutesPoint.X, minutesPoint.Y, "black", 3);

    drawLine(centerX, centerY, hoursPoint.X, hoursPoint.Y, "white", 3);
    var hours = now.getHours();
    if (hours >= 12) { hours -= 12; } // Hours are 0-11
    hoursPoint = getOtherEndOfLine(centerX, centerY, (2 * Math.PI / 12 * hours) + (2 * Math.PI / 12 / 60 * minutes), 0.6 * radius);
    drawLine(centerX, centerY, hoursPoint.X, hoursPoint.Y, "black", 3);
}

为了理解上述内容,有两个辅助函数:

To make sense of the above, there are two helper functions:

  • drawLine(x1, y1, x2, y2, 颜色, 粗细)
  • getOtherEndOfLine(x, y, 角度, 长度)

问题在于,虽然所有的手都按预期绘制成黑色,但它们永远不会被擦除.我希望由于同一条线是用白色(背景色)绘制的,它会有效地擦除之前在该点绘制的内容.但这似乎并非如此.

The problem is that while all the hands get drawn as expected in black, they never get erased. I would expect that since the same line is drawn in white (the background colour) it would effectively erase what was previously drawn at that point. But this doesn't seem to be the case.

我缺少什么吗?

推荐答案

出于我可以扩展的原因,您应该考虑清除您的画布并完全重新绘制它,除非有性能或合成原因不这样做.

For reasons that I could expand upon, you should consider clearing your canvas and redrawing it entirely unless there are performance or compositing reasons not to.

你想要 clearRect,类似这样:

//clear the canvas so we can draw a fresh clock
ctx.clearRect(0, 0, canvasWidth, canvasHeight);

//redraw your clock here
/* ... */

相关文章