This article recently appeared on BuildNewGames.com, a collaboration by the teams at Bocoup and Internet Explorer.
The past year has seen wonderful growth in the popularity of 2D Canvas; it’s been great to see so many people getting comfortable with the 2D context. Canvas is almost synonymous with HTML5 gaming and supported in all modern browsers including Chrome, Firefox, and Internet Explorer 10 and 9.
One thing that many people take for granted is the “bottom to top” canvas drawing order; putting down the background first, then objects in the middle of the scene, and finally drawing the foreground.
It’s true that this is how canvas works by default, and there’s a specific name for it; it’s called the source-over global composite operation (GCO).
What many people don’t know is that you can reverse this order – by setting ctx.globalCompositeOperation = destination-over, you can actually draw the background last, and it will go under what’s already been drawn on your canvas.
There are a total of eleven total GCOs at your disposal. There used to be an even dozen, but the black sheep of the bunch – darker – has unfortunately been abandoned.
Canvas Global Composite Operations
In general, you should use source-atop, because it has been the focus of much optimization and is relatively fast. However, there are times when the scene you’re trying to create is difficult or impossible to pull off with source-atop alone.
The GCO modes apply to every pixel that goes onto the canvas. Whether drawn via fillRect, stroke, drawImage, fillText, or anything else – they are all subject to the active GCO. Happily, as the GCO is set on the canvas context, it is subject to the same save/restore (push/pop) behavior as all the other contextual fields (scale, rotation, fill style, global alpha, etc).
This article will explore two of the lesser known GCOs – source-atop and destination-out – and show how they can help you solve some common problems in game graphics programming. (more…)