globalCompositeOperation影响到所有层吗? [英] The globalCompositeOperation affected to all layers?

查看:63
本文介绍了globalCompositeOperation影响到所有层吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的代码,我想为播放器创建遮罩.

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();

但是globalCompositeOperation影响了级别backgorund.它认为level1背景为蒙版二.如何解决这个问题?谢谢.

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

推荐答案

很难告诉你想要什么.

// 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);

如果需要,但是黑色英雄像素后面的level1图像

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

这篇关于globalCompositeOperation影响到所有层吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆