Skip to content Skip to sidebar Skip to footer

The Globalcompositeoperation Affected To All Layers?

I have got a simple code and i want create mask for the player. ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.drawImage(level1, 0, 0); ctx.save(); ctx.fillRect(0,0,mask.wi

Solution 1:

Hard to tell what you want.

// clear the whole canvas
ctx.clearRect(0, 0, canvas.width, canvas.height); 
// draw image at top left covering part or all of the canvas
ctx.drawImage(level1, 0, 0);

ctx.save();
// fill part of all of the canvas including the drawn image with black
ctx.fillRect(0,0,mask.width,mask.height);

ctx.globalCompositeOperation="source-in";
//draw image where each pixel in the hero image get the hero colour RGB and the// source alpha.
ctx.drawImage(hero,0,0);
ctx.restore();

If mask width and height is the same as the canvas then you will just see the hero image.

Maybe you want just the hero image as black while keeping the level image?

ctx.clearRect(0, 0, canvas.width, canvas.height); 
ctx.fillRect(0,0,mask.width,mask.height);
ctx.globalCompositeOperation="destination-in"; 
ctx.drawImage(hero,0,0);
ctx.globalCompositeOperation = "source-over"; //reset default
ctx.drawImage(level1, 0, 0);

If you want that but the level1 image behind the black hero pixels

ctx.clearRect(0, 0, canvas.width, canvas.height); 
ctx.fillRect(0,0,mask.width,mask.height);
ctx.globalCompositeOperation="destination-in"; 
ctx.drawImage(hero,0,0);
ctx.globalCompositeOperation="destination-over"; 
ctx.drawImage(level1, 0, 0);
ctx.globalCompositeOperation = "source-over"; //reset default

If you want something else you will have to explain a little more or give an example image of what you want and what you get.

There are many situations where you can not do all the compositing on the one canvas. In those situations you create a second off screen canvas

var offScrCan = document.createElement("canvas");
offScrCan.width = canvas.width;
offScrCan.height = canvas.height;
var ctx1 = offScrCan.getContext("2d");

Do the compositing on the off screen canvas then draw that canvas on top of the display canvas

ctx.drawImage(offScrCan,0,0);

Post a Comment for "The Globalcompositeoperation Affected To All Layers?"