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

178
Visualizações
How to fill shape outside on canvas

I work with canvas and draw closed line with the mouse, than fill the inner area by some color(green for example). How do I fill the outer area, not the inner. Here is chunk of code I use:

const context = canvas.getContext('2d')

canvas.addEventListener('mouseup', function (e) {
      context.closePath();
      context.fill();
      draw = false;
});

Here is an example that I want to implement
https://jsfiddle.net/tonycaso/drxpb8vy/24/
But it use fabricjs library, I need to do it by native canvas and js.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can make use of the globalCompositeOperation. It sets the type of compositing operation to apply when drawing new shapes. You might want to read more about it here.

In your case, you can first fill the entire canvas with a color (say, green). Then let the mouse draw the shape. When the shape is drawn, fill it using the global composite operation destination-out. It will cut the shape out from the background resulting in the outer area remaining filled.

const canvas = document.querySelector('canvas');
const context = canvas.getContext('2d');

context.canvas.width = 300;
context.canvas.height = 300;

canvas.addEventListener('mousedown', function (e) {
  context.beginPath();
  context.moveTo(e.clientX, e.clientY);
});

canvas.addEventListener('mousemove', function (e) {
  context.lineTo(e.clientX, e.clientY);
});

canvas.addEventListener('mouseup', function (e) {
  context.closePath();

  // Fill a rect on the entire canvas with the desired color
  context.fillStyle = "green";
  context.fillRect(0, 0, canvas.width, canvas.height);
  
  // Cut out the drawn shape
  context.globalCompositeOperation = "destination-out";
  context.fill();
});
canvas {
  cursor: crosshair;
  border: 2px solid #000;
}
<canvas></canvas>

about 4 years ago · Juan Pablo Isaza Relatório

0

Basically that is really hard. You would need to write a custom function checking every pixel. What we can do to make it easier is

background (what color you want to fill)
fill(the original Background color)
//drawYourShape
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