Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you draw with alpha = 0 in an html5 canvas to 'erase'

How do you draw with alpha = 0 to an HTML5 Canvas? Imagine I'm making a photoshop clone, I have a layer that's solid red. I pick the eraser tool and draw with. It draws in rgba(0,0,0,0) letting me see through to the background. How do I do this in HTML5 Canvas?

Here's some code.

var rand = function(v) {
    return Math.random() * v;
};

var canvas = document.getElementsByTagName("canvas")[0];
var ctx = canvas.getContext("2d");

// fill the canvas with black
ctx.fillStyle = "red";
ctx.fillRect(0, 0, canvas.width, canvas.height);

// Erase some circles (draw them in 0,0,0,0);
ctx.fillStyle = "rgba(0,0,0,0)";
ctx.globalCompositeOperation = "copy";
for (var ii = 0; ii < 5; ++ii) {
    ctx.beginPath();
    ctx.arc(rand(canvas.width), rand(canvas.height), 
            rand(50) + 20, 0, 360, false);
    ctx.fill();
}

/*
source-over    
source-in    
source-out    
source-atop

destination-over    
destination-in    
destination-out    
destination-atop

lighter    
darker    
copy    
xor
*/
canvas {
    margin: 10px;
    border: 1px solid black;
    background-color: yellow;
}
<div>Want red with yellow circles</div>
<canvas></canvas>

This doesn't work. All canvas operations are considered to be infinitely large which means drawing each circle (arc) with globalCompositeOperation set to "copy" effectively erases everything outside of each circle.

I might be able to setup clipping to match the circle but ideally I'd like to be able to erase with an anti-aliased circle, same as a photoshop brush.


1 Answers

You'll want to use:

ctx.fillStyle = "rgba(0,0,0,1)"; // (Drawing with 0 alpha pretty much means doing nothing)
ctx.globalCompositeOperation = "destination-out";

Working Example

Keep in mind to save the previous globalCompositeOperation and restore it, or transparency won't work properly, later on.

The problem is that "Drawing with alpha=0 on a canvas just overlays a invisible layer of "ink", by default.

like image 184
Cerbrus Avatar answered Jan 27 '26 21:01

Cerbrus