I just started working with canvas in HTML5 and with javascript. I'm pretty satisfied with my game so far: http://xenopal.dk/game-v1.1/. But I'd like to implement lighting as well in the style of Terraria or Minecraft http://www.nerd-age.com/wp-content/uploads/2011/09/Terraria-New-Torches.png where you can have multiple light sources, even with color, without it being like realistic shadows that gets casted by the light.

I've tried to do per-pixel lighting, but that didn't go so well since it made my whole game lag like crazy and unplayable. I might have done the per-pixel lighting wrong since I'm fairly new to creating games in canvas.

I hope that you're able to help me or maybe pass on some links to other places that might be able to help. Thank you :)

// Edit - Probably forgot to mention that it should of course be a 2D lighting. I've read somewhere that even with three.js and pixi.js I might be able to create this kind of lighting, but I have no idea on how to do it.


One way to apply light effects with the Context2D is to use the composite operation 'lighter' (globalCompositeOperation='ligther'), and adjust the alpha (globalAlpha= 0.0 to 1.0).
Then you can either :
• Draw the shape of the light with several geometric drawings that create a simple shade to get a cartoonish light effect.
• Define gradients to get a more realistic effect.

I did a small and simple demo here :

enter image description here

You can see that, by using clipping, the left (cartoonish) light does not affect the blue orb.
With a variation based on a simple sin(time) i did the a small oscillation of the light size to add a 'torch' effect.

I hope this can inspire you for your game.
Notice that you could do a multi-pass light rendering that would also darken parts of the canvas : be aware that the 'darken' composite mode does not work on all browsers (sorry i forgot which does what), but anyway it doesn't matter because it is not required : just apply a dark (#000) fillStyle in the default ('source-over') globalCompositeOperation with the right globalAlpha and you'll darken the filled area.

| improve this answer | |
  • \$\begingroup\$ You can move the fiddle into a stack snippet, so that the link doesn't possibly rot in the future (slim possibility, but still there). \$\endgroup\$ – XNargaHuntress Aug 18 '15 at 13:44
  • 1
    \$\begingroup\$ Well i quite agree but for this fiddle i re-used my 'basic' fiddle so there's far too much code that isn't relevant.... I'm sure someone will let me know if jsfiddle goes down !!! :-) \$\endgroup\$ – GameAlchemist Aug 18 '15 at 13:51
  • \$\begingroup\$ Ah, didn't notice the polyfills and setup at first. \$\endgroup\$ – XNargaHuntress Aug 18 '15 at 14:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.