Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

76
Views
How to make one HTML `canvas` path opaque but keep the rest transparent?

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.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!