Gregory Kafanov
Gregory Kafanov

Reputation: 357

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.

Upvotes: 1

Views: 528

Answers (2)

N3R4ZZuRR0
N3R4ZZuRR0

Reputation: 2412

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>

Upvotes: 2

Malte
Malte

Reputation: 33

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

Upvotes: 0

Related Questions