Thorben Croisé
Thorben Croisé

Reputation: 12860

Set pixels of canvas to transparent again

I want to draw an image, erase some parts and then paint again on top. Something along the lines of:

ctx.drawImage(favicon, 0, 0);
ctx.fillStyle = 'transparent';
ctx.fillRect(10, 0, 6, 6);
ctx.fillStyle = 'red';
ctx.fillRect(12, 0, 4, 4);

How do I erase parts of the image?

Upvotes: 0

Views: 507

Answers (1)

markE
markE

Reputation: 105015

.clearRect is a good choice as indicated in the upvoted comment to your question.

If you have non-rectangular area (or just a set of pixels) to make transparent, then you can also use destination-out compositing to make those pixels transparent.

This example starts with the JellyBeans image and cuts out the sun image from it:

Jellybeans

enter image description here

Sun (used as an irregular shape eraser)

enter image description here

Jellybeans with the sun-shape erased

enter image description here

Annotated example code:

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;


var jellybeans=new Image();
jellybeans.onload=start;
jellybeans.src="https://dl.dropboxusercontent.com/u/139992952/multple/jellybeans.jpg";
var sun=new Image();
sun.onload=start;
sun.src='https://dl.dropboxusercontent.com/u/139992952/multple/sun.png';
var imageCount=2;
function start(){

  // wait for all images to load
  if(--imageCount>0){return;}

  // resize the canvas to jellybean size
  canvas.width=jellybeans.width;
  canvas.height=jellybeans.height;

  // draw the jellybeans on the canvas
  ctx.drawImage(jellybeans,0,0);

  // Set compositing to "destination-out"
  // All new drawings will act to erase existing pixels
  ctx.globalCompositeOperation='destination-out';

  // Draw the sun image
  // Drawing will erase the sun image shape from the jellybeans 
  // You could also erase with any drawing commands (lines,arcs,curves,etc)
  ctx.drawImage(sun,100,50);

  // always clean up!
  // Reset compositing to default mode
  ctx.globalCompositeOperation='source-over';

}
#canvas{border:1px solid red; margin:0 auto; }
<h4>Jellybeans with sun-shaped erased</h4>
<canvas id="canvas" width=300 height=300></canvas>

Upvotes: 4

Related Questions