Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

77
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda