HTML 5 Canvas Tutorial – Drop Shadows

While working on the Pulse graphics engine I’m learning all kinds of new techniques and tid bits about Canvas. One of the latest things I’ve been playing around with and working on is creating shadows. This is actually pretty easy with the JavaScript drawing api available for canvas. It actually just takes a few properties set on the canvas context.

Before jumping into the code there are a couple of items to note. First, you can selectively apply a shadow by using the save and restore methods on the context. Second, for performance reasons make sure to draw shadows as infrequently as you can. Now let’s jump into the code.

function bodyloaded() { // Attached to body’s onload event

  var canvas = document.getElementById(‘myCanvas’); // Grabs the canvas element
  var ctx = canvas.getContext(‘2d’); // Grabs the canvas context

  ctx.save(); // Save the state of the context
  ctx.fillStyle = ‘#4433FC’; // Sets the fill color
  ctx.shadowOffsetX = 2; // Sets the shadow offset x, positive number is right
  ctx.shadowOffsetY = 2; // Sets the shadow offset y, positive number is down
  ctx.shadowBlur = 4; // Sets the shadow blur size
  ctx.shadowColor = ‘rgba(0, 0, 0, 0.6)’; // Sets the shadow color
  ctx.beginPath(); // Starts a shape path
  ctx.arc(150, 150, 75, 0, 2 * Math.PI, false); // Draws a circle
  ctx.fill(); // Fills the path
  ctx.restore(); // Restore the state of the context

  ctx.fillStyle = ‘#DE33FC’; // Sets the fill color
  ctx.beginPath(); // Starts a shape path
  ctx.arc(350, 350, 60, 0, 2 * Math.PI, false); // Draws a circle
  ctx.fill(); // Fills the path
}

That’ll spit out something like the following.

Looking at the code it starts out by grabbing the canvas and then the context from the canvas. In order to apply the drop shadow to only a part of the canvas we have to use the save and restore functions on the context. The next thing done is to set the appropriate properties on the canvas context.

  • shadowOffsetX – the horizontal offset for the drop shadow
  • shadowOffsetY – the vertical offset for the drop shadow
  • shadowBlur – the size of the blur of the drop shadow
  • shadowColor – the color of the drop shadow

At a minimum the shadowBlur and shadowColor properties have to be set in order for the shadow to be used. The color can be set with any of the formats available for fill style or stroke color. I’d recommend using the ‘rgba’ format so you can set the alpha on the color.

That wraps it up for this tutorial. Make sure to check out some of other canvas tutorials here on the site. If you have any questions or comments, feel free to leave them below.

If you’re looking for more information on HTML5 Canvas. Check out these great books:

Leave a Reply

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