canvas Effects

The canvas object is relatively simple to work with, but it isn't as sophisticated as SVG. For instance, it lacks many of the SVG filter effects, as well as several of the primitive shapes. It also doesn't have the ability to add dashes or markers to objects. Most of these problems can be somewhat countered by using functions, but doing so adds to the complexity of creating images.

On the other hand, the canvas object does provide support for two important effects: gradients and transforms. It also has some fun image functions that allow us to do some interesting tweaks.


Gradients in canvas are quite similar to those in SVG. They're created as linear or radial gradients, and color stops can be defined to make more complex effects. Once a gradient is created, it can be used with either stroke or fill, directly assigned to either strokeStyle or fillStyle.

The function to create a linear gradient is createLinearGradient, and it takes the coordinates for the stop and end points of the gradient, given as relative pixel locations:

var lgFirst = ctx.createLinearGradient(0,0, 0.95, 0.95);

The function to create a radial gradient is createRadialGradient. It takes six arguments: three to define one circle and three to define a second. Of the circle measurements, the first two are for the relative coordinate (x,y), and the third is the circle radius:

var rgFirst = ctx.createRadialGradient(0,0,20,150,210,10);

To modify the gradient stops, use the addColorStop, passing in a ...

Get Painting the Web 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.