Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>One trivial way would be to use <code>imageData</code> but that would be painfully slow. It's an option, but not a good one for a game engine.</p> <p>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:</p> <p><a href="http://jsfiddle.net/HADky/" rel="noreferrer">http://jsfiddle.net/HADky/</a></p> <p>Or see it with an image behind: <a href="http://jsfiddle.net/HADky/10/" rel="noreferrer">http://jsfiddle.net/HADky/10/</a></p> <p>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.</p> <p>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.</p> <p>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.</p> <hr> <p><strong>EDIT:</strong> Hey! So I've done a bit of thinking and came up with a good solution.</p> <p>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:</p> <p><img src="https://i.stack.imgur.com/MLfs7.png" alt="enter image description here"></p> <p>Then you want to set the fill style to your ambient color and set the globalCompositeOperation to xor and xor the whole thing.</p> <pre><code>ctx.fillStyle = amb; ctx.globalCompositeOperation = 'xor'; ctx.fillRect(0,0,500,500); </code></pre> <p>That will leave you with the "opposite" image except the transparent parts will be correctly ambient:</p> <p><img src="https://i.stack.imgur.com/695Vv.png" alt="enter image description here"></p> <p>Here's a working example of the code:</p> <p><a href="http://jsfiddle.net/a2Age/" rel="noreferrer">http://jsfiddle.net/a2Age/</a></p> <p>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:</p> <p><a href="http://jsfiddle.net/a2Age/2/" rel="noreferrer">http://jsfiddle.net/a2Age/2/</a> Hope that helps!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload