I recently started learning about drawing to the HTML canvas with javascript and made a simple game where a blackhole eats planets, with two canvas', one for the background and one for the game-play.
<body>
<canvas id="game-board"></canvas>
<canvas id="background"></canvas>
<script src="gameplay.js"></script>
<script src="bg.js"></script>
</body>
Even though I thought I set the background color of the game-board to black...
ctx.fillStyle = '#000';
ctx.fillRect(0, 0, canvas.width, canvas.height);
...it shows as transparent, which seems strange but is actually exactly what I want.
But now I'm trying to draw a "blackhole" (just a black circle with faded edges) on top of it, but it also is always showing as transparent with regard to the other canvas, which is not what I want.
draw() {
let gradient = ctx.createRadialGradient(
holePosition.x,
holePosition.y,
holeRadius / 2,
holePosition.x,
holePosition.y,
holeRadius * 2
);
gradient.addColorStop(0, 'rgba(0,0,0, 1)');
gradient.addColorStop(1, 'rgba(0,0,0, 0)');
ctx.beginPath();
ctx.arc(holePosition.x, holePosition.y, holeRadius * 2, 0, Math.PI * 2);
ctx.fillStyle = gradient;
ctx.fill();
ctx.closePath();
}
The blackhole correctly "blacks out" things on it's own canvas (you can see when you move it over the planets that appear), but it's still transparent with regard to the other canvas below it in the HTML showing all the stars.
So how can I make it so the blackhole also "blacks out" the other canvas behind it?
Codesandbox (move around with arrow keys)
I've played around with ctx.globalAlpha and ctx.save()/ctx.restore() but with no success.