我想用纯 JavaScript 在画布上制作一个虚线圆圈,它会随着鼠标指针移动。圆圈没有(实心)填充。我以为只要再涂一遍ctx.globalCompositeOperation = "xor";
就可以删除它,但这不起作用。为什么不?我现在需要使整个边界矩形无效吗?
let g_ctx = undefined;
function drawCircle(ctx, x, y) {
const radius = 50;
ctx.beginPath();
ctx.arc(x, y, radius, 0, 2 * Math.PI);
ctx.closePath();
ctx.lineWidth = 1;
ctx.strokeStyle = 'red';
//ctx.setLineDash([3, 3]);
ctx.stroke();
// This will be removed, but shows the 'xor'-paint in action.
ctx.fillStyle = 'blue';
ctx.fillRect(0, 0, 100, 100);
ctx.fillStyle = 'red';
ctx.fillRect(50, 50, 100, 100);
} // drawCircle
function onClick(event) {
drawCircle(g_ctx, 300, 200); // remove circle does not work.
// Can I use 'this' in onClick or some member of event,
// so I won't need g_ctx???
}
const onLoad = function() {
let canvas = document.getElementById("canvas");
let ctx = canvas.getContext('2d');
ctx.globalCompositeOperation = "xor";
g_ctx = ctx;
canvas.addEventListener('click', onClick, false);
drawCircle(ctx, 300, 200);
}
window.addEventListener("load", onLoad);
在 html 中:
<body>
<canvas id="canvas" width="600" height="300"></canvas>
</body>
我曾希望,当使用 xor-paint 第二次(或偶数次)绘制圆时,就在旧圆的顶部,它会被有效地移除,显示原始背景。
当鼠标移动时,我需要删除圆圈并在新位置重新绘制它。(我稍后会处理鼠标移动)。