The globalCompositeOperation affected to all layers?

只愿长相守 提交于 2019-12-24 19:18:29

问题


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.width,mask.height);
ctx.globalCompositeOperation="source-in";
ctx.drawImage(hero,0,0);
ctx.restore();

But globalCompositeOperation affected level backgorund. It considers level1 backround is mask two. How can this problem be solved? Thanks.


回答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);


来源:https://stackoverflow.com/questions/43836443/the-globalcompositeoperation-affected-to-all-layers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!