Wrapping Your Head Around Canvas: Part 3

We’ve only truly begun to scratch the surface of possibilities with our little series about Canvas, and as we journey deeper into the API you can see the benefits that it has over Flash technology concerning mobile device/browser support.

Today I’d like to continue our adventures in learning the basics by talking about working with images and text.

Working with Images

It’s time to introduce the drawImage method that does exactly what you thought it would, it inserts images. Just like with patterns we’ll have to wait for the image to load before you can initialize drawImage. Let take a quick look:

ctx.drawImage(imageOjb, dX, dY);

Using the onload property of the image object, should place it on your canvas. Your code should look similar to this:

window.onload = function() {
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");

var dX = 20;
var dY = 20;

var imageObj = new Image();
imageObj.onload = function() {
imageObj.src = "zombies.jpg";

That wasn’t too hard was it? Now you can add images all over your canvas. The script above results in the image being placed at the coordinates of 69, 50 on our canvas. Below you can see how our fore into images turned out:

To resize an image using Javascript you only have to modify the existing code from earlier by adding a width and height property:

var dX = 20;
var dY = 20;
var dWidth = 420;
var dHeight = 250;

var imageObj = new Image();
imageObj.onload = function() {
context.drawImage(imageObj, dX, dY, dWidth, dHeight);

Now we’re getting into the cool stuff and we’re going to crop, invert colors, and pixelate the image.

So let’s say you like everything you’ve been able to create up until this point using canvas, but now you’d like to crop the photo you inserted earlier. That’s no problem, you’ve got that covered by introducing some new variables into your JavaScript called sourceX, sourceY, sourceWidth, and sourceHeight.

var sourceX = 150;
var sourceY = 0;
var sourceWidth = 150;
var sourceHeight = 150;

Now we’ll change the destination X, Y, Width, and Height to parse through the variables we created above.

var dX = canvas.width/2 - dWidth/2;
var dY = canvas.height/2 - dHeight/2;
var dWidth = sourceWidth;
var dHeight = sourceHeight;

var imageObj = new Image();
imageObj.onload = function() {
    context.drawImage(imageObj, sourceX, sourceY, sourceWidth, sourceHeight, dX, dY,
dWidth, dHeight);

The parameters listed help us define the location and size that we’d like to crop out of the image. The resulting image should be a 150px x 150px thumbnail.


Canvas allows you to render text and specify size, font, alignment and baselines. Just like you would with your custom shape, you can also fill the text and add strokes. After you set your variables for the X and Y positions, adding text on to your canvas isn’t much different from writing the CSS for a stylized heading. Let’s take a look:

window.onload = function() {
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');

var x = 150;
var y = 100;
ctx.font = "20pt Arial";
ctx.fillText("Hello World. Canvas is Awesome!", x, y);

The fillText method passes one parameter and two variables. The first argument is your text that you would like to appear on the canvas, in this case “Hello World. Canvas is awesome!”. Then we call the arguments for the X and Y coordinates for the text to be placed on the canvas. The font and fillText properties are what will make or break rendering your text. In the example above you’ll notice that the font method sets the font type and size, whereas the fillText method actually contains our text and it’s X and Y coordinates.

Stereoscopic Effect

Harken back to the days of awesome black and with films using anaglyph techniques to create eye popping 3D effects. Utilizing the anaglyph method of superimposing a red and cyan image then offsetting them to create the illusion of depth, we can make our text pop off of the screen as well. Let’s begin by looking at our CSS for this effect:

text-shadow: -0.06em 0 0 red, 0.06em 0 0 cyan;

There is no shadow blur for this effect. By using the fillText property we can get the same results:

var text = “Hello world!”
ctx.fillStyle = “#000”
ctx.fillText(text, -7, 0);
ctx.fillStyle = “red”
ctx.fillText(text, 0, 0);
ctx.fillStyle = “cyan”
ctx.fillText(text, 7, 0);

We’ll need to convert the em’s to pixels, because the em unit or measurement isn’t supported in canvas. By using the code below we can find the ratio and create an element with the same properties in the DOM and setting the width of the format:

var font = “20px sans-serif”
var d = document.createElement(”span”);
d.style.cssText = “font: “ + font + “ height: 1em; display: block”
// the value to multiply PX’s by to convert to EM’s
var EM2PX = 1 / d.offsetHeight;

Text Drop Shadow

Much like creating a drop shadow for an object with the advent of CSS3, you can create shadows in canvas. There are two distinct differences though between the two. Were a CSS drop shadow utilizes two properties (box-shadow and text-shadow), canvas only utilizes one that is used for vector elements. You can use canvas shadows by using these four properties:

  • shadowColor
  • shadowBlur
  • shadowOffsetX
  • shadowOffsetY

Let’s create a simple text shadow to show you how each property is used:

ctx.shadowColor = #333;
ctx.shadowBlur = 8;
ctx.shadowOffsetX = 3;
ctx.shadowOffsetY = 2;

With your blur property keep in mind that the higher you go in value the larger the blur will increase. You can create a similar effect that will mimic a neon glow as well using these 4 values. Take a moment or two to play around with the effect a bit.


That about wraps it up for part 3 of our canvas series. And in my next article we’ll discuss some more advanced techniques with Canvas and start getting into animation and particles. We’re also going to take what we’ve learned so far and start building a simple project using canvas.

I wanted you to understand the core foundations of the technology before we started working on our project together. If anyone has any questions make sure to leave them in the comments section and I will do my best to answer them.

Josh is currently the Creative Director at Rappsody Studios located in Jacksonville, FL and has been working in across the web for close to eight years. He has a soft spot for front-end development and comics. More articles by Joshua Rapp
Home CSS Deals HTML HTML5 Java JavaScript jQuery Miscellaneous Mobile MySQL News PHP Resources Security Snippet Tools Tutorial Web Development Web Services WordPress