Canvas Blend Modes in Safari on Desktop and iOS7

Blend Modes have probably been one of the most highly requested features in canvas. Canvas is great for gaming and rich visual effects down to the pixel level, and though we can do shaders and GPU enhanced effects in webGL, we don't always want the overhead of it's more verbose API. 2D Canvas exposes a much simpler API for blending content. To blend elements drawn on the canvas with the content below it we simply set the globalCompositeOperation property of our canvas context to the blend mode we want. This involves a comparison and interpolation of values based on the destination, pixels drawn before we set the composite operation, and the source, pixels drawn after we set the composite operation. In the example below, we are setting it to multiply which multiplies the source and destination color.

context.globalCompositeOperation = 'multiply';

We have access to many of the same blend modes designers are familiar with from tools like Photoshop and Illustrator. We also have access to alpha compositing operations in this same way, which use the pixel values of the source and the destination and adjust the alpha based on the interpolated values. Using this we could easily draw transparent pixels on the destination in the shape of a source image or drawn shape. For a full list of all the available blend and compositing modes, visit the spec. You can see a demo I put together for a talk I did at PhoneGap Day, which utilizes canvas blend modes here.

These features will be useful for ambient effects, explosions and other special effects in games and other rich media applications. Today these are available on Fire Fox, the new Safari 7, and on mobile in iOS7. It can also be enabled in Chrome under about://flags "Enable experimental Web Platform features". As always you can keep track of the support status of these features on caniuse.com.

Leave a Reply

Your email address will not be published. Required fields are marked *