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

119
Vistas
Adding transparency/alpha to canvas overwriting existing color

I am trying to create a moon shape with canvas. Therefor I created two circles: One being filled with my color, another one being subtracted using globalCompositionOperation: "destination-out".

const moonCanvas = createCanvas(WIDTH, HEIGHT);
const moonCtx = canvas.getContext("2d");

moonCtx.beginPath();
moonCtx.arc(WIDTH / 2, HEIGHT / 2, HEIGHT / 4, 0, 2 * Math.PI);
moonCtx.fill();

moonCtx.globalCompositeOperation = "destination-out";

moonCtx.beginPath();
moonCtx.arc(WIDTH / 2 + 30, HEIGHT / 2, HEIGHT / 4, 0, 2 * Math.PI);
moonCtx.fill();

Here's a fiddle with a minimal reproduction: https://jsfiddle.net/h2qbytzn/

The problem now is that there is "explicit" transparency added to the canvas by this operation. Whenever I want to add the moon to another canvas, it also includes the transparent parts and thus overwrites what is already there on there canvas.

Is there a way to import the canvas contents while ignoring the transparent parts?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

What worked for me now is creating a second canvas, painting my objects there and merging them into the original canvas with drawImage:

const c2 = createCanvas(WIDTH, HEIGHT);
const ctx2 = c2.getContext("2d");

ctx2.fillStyle = "yellow";

ctx2.beginPath();
ctx2.arc(WIDTH / 2, HEIGHT / 2, HEIGHT / 4, 0, 2 * Math.PI);
ctx2.fill();

ctx2.globalCompositeOperation = "destination-out";

ctx2.beginPath();
ctx2.arc(WIDTH / 2 + 30, HEIGHT / 2 - 15, HEIGHT / 4, 0, 2 * Math.PI);
ctx2.fill();

ctx.drawImage(c2, 0, 0); // merging the canvas, not its context!
about 4 years ago · Juan Pablo Isaza Denunciar
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