I want to make a dashed circle on a canvas in pure JavaScript, that moves to follow the mouse pointer. The circle has no (solid) fill. I thought that by just painting over it again with ctx.globalCompositeOperation = "xor";
would remove it, but that does not work. Why not? Do I now need to invalidate an entire bounding rectangle?
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);
In html:
<body>
<canvas id="canvas" width="600" height="300"></canvas>
</body>
I had hoped that when the circle is drawn for the 2nd time (or an even number of times) with xor-paint, right on top of the old one, that it would effectively be removed, showing the original background.
I need to remove the circle and redraw it on a new position when the mouse moves. (I will work on handling mouse moves later).