Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

118
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda