HTML5 and CSS3, Second Edition

(singke) #1

Adding Gradients to Objects


We set the stroke and fill color for the drawing tools when we started, like
this:

html5_canvas/logo.html
context.fillStyle="#FF0000";
context.strokeStyle="#FF0000";

But that’s a little boring. Let’s create gradients and assign those to strokes
and fills:

html5_canvas/logo_gradient.html
vargradient= context.createLinearGradient(0,0, 0, 40);
gradient.addColorStop(0, "#AA0000");// darkerred
gradient.addColorStop(1, "#FF0000");// red
context.fillStyle= gradient;
context.strokeStyle= gradient;

We create a gradient object and set the gradient’s color stops. In this example,
we’re just going between two shades of red, but we could do a rainbow if we
wanted. (Please do not do a rainbow.)

Note that we have to set the color of things before we draw them.


At this point, our logo is complete, and we have a better understanding of
how to draw simple shapes on the canvas. However, versions of Internet
Explorer prior to 9 don’t have any support for the <canvas> tag. Let’s fix that.

Falling Back


Google released a library called ExplorerCanvas that makes most of the
Canvas application programming interface available to Internet Explorer
users.^1 At the time of writing, the most stable release, version 3.0, doesn’t
support adding text at all, and hasn’t been updated since 2009. So we’ll use
the version from the Subversion repository, which works much better but
still has some limitations (which you can read about in the library’s source
code).^2 To make it work, we include this library in the <head> section of the
page:

html5_canvas/logo_gradient.html
<!--[iflte IE 8]>
<scriptsrc="javascripts/excanvas.js"></script>
<![endif]-->

and then we add these lines right above where we detect the canvas:



  1. http://code.google.com/p/explorercanvas/

  2. http://explorercanvas.googlecode.com/svn/trunk/excanvas.js


Chapter 6. Drawing in the Browser • 118


Download from Wow! eBook <www.wowebook.com> report erratum • discuss

Free download pdf