[RECIPE]: draw a hole inside HTML canvas

[RECIPE]: draw a hole inside HTML canvas

Imaging you (for any reason) need to draw some color area of complicated form in HTML canvas, and then cut a piece of it, like a donut.

There is code sample for this trick:

ctx.beginPath(); // start path drawing
ctx.moveTo(startX, startY);
for (let point of points) {
	ctx.lineTo(point.x, point.y);
}
ctx.closePath(); // complete line draiwng 
ctx.fillStyle = 'red';
ctx.fill();
// we need lines as well
ctx.stroke();

// at this moment we have our path drawn and filled with color
// draw a donut hole


ctx.beginPath(); // again - new path for are to cut
ctx.moveTo(cutStartX, cutStartY);
for (let point of holePoints) {
	ctx.lineTo(point.x, point.y);
}
ctx.closePath(); // complete line draiwng 

// magic
ctx.clip();
// clear area, but only area inside recent path will be cleared
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.stroke();