Canvas - Fill a rectangle in all areas that are fully transparent

萝らか妹 提交于 2019-11-28 08:48:34

One trivial way would be to use imageData but that would be painfully slow. It's an option, but not a good one for a game engine.

Another way would be to think of the ambient light and the light-source as if they were one path. That would make it very easy to do:

http://jsfiddle.net/HADky/

Or see it with an image behind: http://jsfiddle.net/HADky/10/

The thing you're taking advantage of here is the fact that any intersection of a path on canvas is always only unioned and never compounded. So you're using a single gradient brush to draw the whole thing.

But it gets a bit trickier than that if there's more than one light-source. I'm not too sure how to cover that in an efficient way, especially if you plan for two light-sources to intersect.

What you should probably do instead is devise an alpha channel instead of this overlay thing, but I can't currently think of a good way to get it to work. I'll revisit this if I think of anything else.


EDIT: Hey! So I've done a bit of thinking and came up with a good solution.

What you need to do is draw a sort of alpha channel, where the dark spots mark the places where you want light to be. So if you had three light sources it would look like this:

Then you want to set the fill style to your ambient color and set the globalCompositeOperation to xor and xor the whole thing.

ctx.fillStyle = amb;
ctx.globalCompositeOperation = 'xor';
ctx.fillRect(0,0,500,500);

That will leave you with the "opposite" image except the transparent parts will be correctly ambient:

Here's a working example of the code:

http://jsfiddle.net/a2Age/

Extra optimization: You can actually achieve the effect without using any paths at all, by simply drawing the exact same radial gradients onto rects instead of circular paths:

http://jsfiddle.net/a2Age/2/ Hope that helps!

Just an idea, but since you're getting the opposite effect you're going for from your gradient, have you tried reversing the gradient?

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