Working with the context state stack to save and restore styles

When creating more complex HTML5 canvas applications, you'll find yourself needing a way to revert back to previous style combinations so that you don't have to set and reset dozens of style properties at different points in the drawing process. Fortunately, the HTML5 canvas API provides us with access to the context state stack which allows us to save and restore context states. In this recipe, we'll demonstrate how the state stack works by saving the context state, setting the global alpha, drawing a transparent circle, restoring the state stack to the state before we set the global alpha, and then drawing an opaque square. Let's take a look!

Getting ready...

Before we cover the canvas ...

Get HTML5 Canvas Cookbook 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.