How do I procedurally create a directional light cone with an HTML canvas?

To create a directional light effect, I want to draw this kind of transparency mask on an HTML canvas (using context2d):

I also want to be able to generate such a mask dynamically. I've tried using arc to create this kind of light cone, but I'm not able to draw nice, smooth and naturally looking light.

How can I do this?

• Are you using webGL or the context2d ? – GameAlchemist Oct 12 '14 at 9:29
• I use context2d – jesper Oct 12 '14 at 16:21
• Then you might use the 'ligther' globalCompositeOperation an either a solid fill or a gradient, playing on globalAlpha. You'll have to tweak the color/gradient/alpha to make it nice. Obviously, real shadow need more work (to stop on walls), but you can already improve that with some clipping. Small example with colors/gradient/clipping here : jsfiddle.net/gamealchemist/pgb3bhxj – GameAlchemist Oct 12 '14 at 18:49

When you want a really advanced light engine where objects create shadows, you should look into WebGL and use a 3d engine.

But when you don't need accurate shading and only want objects to create cones of light which illuminate the canvas without respect to content, this is what you could do.

1. Have two canvases, the normal scene and a second background canvas
2. Draw your scene with normal illumination on the front canvas
3. Fill the second canvas all black, and then draw the lights on them.
4. Draw the lightmap to the game scene using globalCompositeOperation = "multiply"

Areas which are all black on the lightmap will also be black in the final output (dark). Areas which are pure white, will be drawn the way they were originally on the input bitmap (bright). Any shades in between will be in twilight. You can also use colors in your lightmap.

Here is a jsfiddle demo:

http://jsfiddle.net/1odkyj42/2/

A word of warning, though: It doesn't work in Internet Explorer because MSIE doesn't support the multiply composite operation yet (even in Version 11). There are workarounds for that, but that's a different topic for a different questions.

• I know the theory and I know that I should composite two layers with proper globalCompositeOperation value. All your examples have simple shapes, like circles, arces. The thing I have problem with is that I can't draw light cone shape. I need to generate smooth light cone with grayscale palette and then overlay it on base layer. – jesper Oct 13 '14 at 16:36
• @jesper Ah, you want to know how to draw a gradient. I updated the jsfiddle in the answer to use one. It would be better when HTML5 would support radial gradients, but unfortunately it only supports linear ones. – Philipp Oct 13 '14 at 19:50
• Yes, it's better but still cone has sharp edges and I would like it to be smooth. – jesper Oct 13 '14 at 21:00