HTML5 Canvas: Shadows

Jakob Jenkov
Last update: 2014-06-15

It is possible to add shadows automatically to shapes drawn on an HTML5 canvas. Here are a few examples:


HTML5 Canvas not supported

The shadow is controlled via these four 2D Context properties:

  1. shadowOffsetX
  2. shadowOffsetY
  3. shadowBlur
  4. shadowColor

shadowOffsetX and shadowOffsetY sets how far from the drawn shape the shadow is to be drawn. Positive values means that the shadow is drawn to the right of (x), and below (y) the shape. Negative values means that the shadow is drawn to the left of (x) and above (y) the shape.

shadowBlur sets how much the shadow should be blurred. The higher this number is, the more blurred the shape becomes. The lower the number is, the sharper the shadow becomes. A value of 0 means that the shadow is not blurred at all.

shadowColor simply sets the color of the shadow.

Here is the code for the example above:

var canvas  = document.getElementById("ex1");
var context = canvas.getContext("2d");

context.shadowOffsetX = 10;
context.shadowOffsetY = 10;
context.shadowBlur    = 4;
context.shadowColor   = "#666666";  //or use rgb(red, green, blue)

context.fillStyle = "#000000";
context.fillRect(10,10, 50, 50);

context.fillStyle = "#000066";
context.font = "30px Arial";
context.fillText("HTML5 Canvas Shadow", 10,120);

Jakob Jenkov

Featured Videos















Core Software Performance Optimization Principles




Advertisements

High-Performance
Java Persistence
Close TOC

All Trails

Trail TOC

Page TOC

Previous

Next