Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

177
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!