为了尝试使用 HTML5 canvas,我决定制作一个可以绘制模拟表盘的应用程序。一切都很好,除了旧行不会以我期望的方式被删除。我在下面包含了部分代码 - DrawHands() 每秒调用一次:
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);
}
为了理解上面的内容,有两个辅助函数:
- drawLine(x1, y1, x2, y2, color, thickness)
- getOtherEndOfLine(x, y, Angular , 长度)
问题是,虽然所有的手都按预期绘制成黑色,但它们永远不会被删除。我希望因为同一条线是用白色(背景色)绘制的,所以它会有效地删除之前在该点绘制的内容。但事实并非如此。
有什么我想念的吗?
最佳答案
与其删除您不想要的内容,您还可以:
- 保存 Canvas 的状态
- 画出你不想要的东西
- 将 Canvas 恢复到保存状态以“删除”它们
这可以使用 ImageData
很容易地完成:
var canvas = document.querySelector('canvas'),
context = canvas.getContext('2d');
context.fillStyle = 'blue';
context.fillRect(0,0,200,200);
// save the state of the canvas here
var imageData = context.getImageData(0,0,canvas.width,canvas.height);
// draw a red rectangle that we'll get rid of in a second
context.fillStyle = 'red';
context.fillRect(50,50,100,100);
setTimeout(function () {
// return the canvas to the state right after we drew the blue rect
context.putImageData(imageData, 0, 0);
}, 1000);
<canvas width=200 height=200>
关于javascript - 删除之前在 HTML5 Canvas 上绘制的线条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7365436/