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

181
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 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