Applying Canvas Effects

As this chapter wraps up, there are a couple additional effects worth covering that Canvas provides: shadows and composition effects.

Adding Shadows

The Canvas context provides a way to add drop shadows to any drawn element, including text, rectangles, paths, and images. This is controlled via a set of four properties on the context:

    // CSS color shadow, accepts RGBA, RGB, hexadecimal
  ctx.shadowColor = "rgba(255,255,255,0.5)"; 
  
  ctx.shadowOffsetX = 4;    // horizontal shadow offset
  ctx.shadowOffsetY = 4;    // vertical shadow offset
  ctx.shadowBlur = 10;      // distance for shadow to fade out

You can use shadows to generate normal drop-shadow effects by using darker shadowColor values or give a subtle glow effect by setting the shadow offset values to zero and using a lighter color.

WARNING Elements with shadows are significantly more processor-intensive to draw than elements without, so use shadows sparingly and consider prerendering effects to an offscreen canvas buffer.

Using Composition Effects

The Canvas context also provides a property called globalCompositeOperation, which controls how Canvas combines existing content with new elements drawn on canvas. The specification defines 11 different possible values for this property, with the default value source-over placing newly drawn elements over the existing content as you would expect.

Unfortunately as of this writing, consistent cross-browser support for the interesting composite operations is poor, so ...

Get Professional HTML5 Mobile Game Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.