HTML Canvas – torch / lightbeam

I’ve been playing around with the HTML Canvas tonight, and having a think about how I’d go about implementing a torch / light beam type effect in a platform game.

There are loads of ways to do this kind of thing, but where I usually start is with the most simple, basic (and shitty) implementation and go from there. I did some searching around the internet and found next to nothing for someone who doesn’t want to use a library, so here’s a starting point.

What I was after was the ability to draw a scene, as you normally would, and then have only a small section lit (or visible) at any one time. The lit section of the scene would be determined where the player’s torch was pointing. To me, the most basic and simple way to achieve that would be to draw the scene on one canvas, then draw a clipping mask on a separate, temporary canvas and then overlay it over the main scene canvas.

Sounds workable in theory, and a starting point at least, but the question is how? There’s a few options – you could draw a masked image over the top – a PNG with a solid background colour and transparent section representing the torchbeam – but that seemed a bit restrictive to me. I want to be able to wobble the torchlight around as the player moves and runs.

In the end, the best solution seemed to be to use the excellent compositing operations offered by the HTML Canvas:

lightCanvas.globalCompositeOperation = 'xor';
lightCanvas.arc(100, 100, 100, 0, 2 * Math.PI);

What does that code do?

It first fills the ‘lighting canvas’ with solid black, entirely. It then performs a ‘xor’ (or ‘exclusive-or’) global composite operation.


What this means in practice, is that it effectively compares what was on the lighting canvas before the operation began (i.e. solid black filling the canvas), and after (i.e. the arc) – and areas where the newly drawn arc overlaps with what was there previously are made transparent.

The end result, is a clipping mask that can be overlaid over the ‘main’ canvas. You can shape the torch beam, you can move it around, you could use gradients to simulate the light faltering – plenty of options there. And a good starting point for playing around with this kind of stuff.

Leave a Reply