Shadows are a great way to make your 2D drawings pop out. They’re very easy to set up and you’re given a couple properties to get you started.
Clear your script and add this bit of code.
var canvas = document.getElementById( 'myCanvas' );
if( canvas.getContext )
var context = canvas.getContext( '2d' );
context.shadowColor = "#666666";
context.shadowOffsetX = 10;
context.shadowOffsetY = 10;
context.shadowBlur = 6;
context.fillStyle = "#00ff00";
context.fillRect(0, 0, 50, 50);
In the above example we use the 4 main shadow properties and draw a green rectangle onto the canvas. Let’s focus on the 4 properties introduced here.
- shadowColor – This property allows you to change the color of the shadow. This can be written in hex code, name, RGB, RGBA, HSL, and HSLA.
- shadowOffsetX – This property defines how far from the drawing should the shadow be via it’s x position. This is measured in pixels. The shadow’s origin point is relative to the drawing’s x coordinate.
- shadowOffsetY – This property defines how far from the drawing should the shadow be via it’s y position. This is measured in pixels. The shadow’s origin point is relative to the drawing’s y coordinate.
- shadowBlur – This property defines how blurry the shadow should be. This is measured in pixels. If you would like no blur, then set this to 0 or don’t even set it at all.
Try opening your document and you should see our shadow now. A couple of things to know. In Safari, the shadow will not appear for gradients. We’ll learn more about gradients in the next tutorial.
You should also know that these properties will apply to all drawings created. So, it’s always a good to reset these properties to the default value by using the save() and restore() methods. By default, the shadow color is black, the offsets are 0 and the blur is also 0.
All properties are supported in all major browsers and on mobile devices. For more information on shadows and canvas, then go here.