If you’ve made it this far in the series you should have a core understand on the basics and how all of them fit together inside of Canvas.

Unfortunately for you, you’re used to my terribly dry sense of humor as well.

Congratulations are in order though if you’ve stuck it out, because today we’ll be diving into some of the more advanced 2D Canvas API features. To be a tad more specific I’m talking about beginning to use the animation. The animation features that we see coming out of Canvas have been referred to the major portion of Canvas that will help put the nail in Flash’s coffin.

This article is going to get a bit more code heavy than its predecessors, so for those of you that may be reading this on a hand held device, I suggest you view the article at your computer to get the full experience. There had been some comments in my previous articles that the code examples get cut off on the edge of the screen when viewed on a mobile device.

Continuing with Images

There was so much to actually cover in my last article on images that I did not get around to all of it. We covered stuff like loading an image and scaling it in your Canvas, now I’d like to discuss ways to play with the image and even save it. Isn’t this exciting! Our example image of the approaching zombies worked quite well, but what if you really wanted to take it back to basics and give it that Grayscale look like George A. Romero’s 1968 classic ‘Night of the Living Dead’?

In order to do that we can calculate the brightness of each pixel in the image, then adjust the Red, Blue, and Green (RGB) in the picture to match the brightness. First we’ll begin with loading the image into our Canvas, like so:

window.onload = function(){
     var imageObj = new Image();
     imageObj.onload = function(){
          drawImage(this);
     };    

     imageObj.src = "zombies.jpg";
};

Once are image has been loaded we can load the Canvas and set our X and Y coordinates. We’re going to employ a new method here as well called getImageData and putImageData. These methods work on the images data, obviously, and the context of our Canvas. Understand that each pixel is represented in RGB and an alpha property, if manipulated properly we can parse the results through to the Canvas using the putImageData method. For you ActionScript enthusiasts out there this should be a familiar operation.

function drawImage (imageObj) {
     var canvas = document.getElementById("myCanvas");
     var ctx = canvas.getContext("2d");

     var dX = 20;
     var dY = 20;

     ctx.drawImage (imageObj, dX, dY);

     var imageData = ctx.getimageData(0, 0, canvas.height, canvas.width);
     var data = imageData.data

Now it’s time to list the variables for the data (ie; the Red, Blue, Green, and Alpha properties) using for:

 for (var i = 0; i < data.length; i += 4) {
          var brightness = 0.34 * data[i] + 0.5 * data[i +1] + 0.16 * data[1 + 2];

          data[i] = brightness; // red
          data[i + 1] = brightness; // green
          data[i + 2] = brightness; // blue
          data[i + 3] = brightness; // alpha
     }

     ctx.putImageData(ImageData, 0, 0);
}
Right Click to Save this Image!

The resulting image in your canvas should now be in Grayscale mode. It’s not exactly anything to really shake a stick at, but it is a rather interesting. Now that we know how to change the RGB of our image, let’s take a look at saving what we’ve created in our Canvas. In order to do so, we’ll be using the getDataURL() method which converts your Canvas into a 64 bit encoded PNG URL. Setting up the variable is rather simple and up until this point in our adventure in HTML5 Canvas setting up the Canvas properties has been the simplest operation, so let’s take a look:

var Data = canvas.getDataURL();

So for our purposes here we can add a variable to the bottom of the script:

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

          // Image or Canvas drawing content

     var dataURL = canvas.toDataURL();

     document.getElementById("canvasImg").src = dataURL;
};

When writing your HTML there are a couple things you’ll need to consider, like the ‘onmousedown’ function in the <body> tag, set it to: return false; . Also make sure that your drawing or image has an id of ‘canvasImg‘. From here when you right click on your canvas area you should be able to save the drawing or image you’ve created.

Basic Animations

The most basic form of animation is to clear the current Canvas state and redraw the object. After we initialize Canvas, the following example shows us how to use the clearRect() method to clear our Canvas bitmap:

function clearCanvas() {
          var canvas = document.getElementById("yourObject");
          var ctx = canvas.getContext("2d");
          ctx.clearRect(0, 0, canvas.width, canvas.height);

Seems simple enough, now let’s begin to set the stage for our animation. You’ll want to load the JS library of your choice, for the purpose of this tutorial I decided to go with jsAnim. The current release of jsAnim was created by Kevin Dolan and it’s free to use, so have fun. Let’s get around to loading our external JS files.

<script type="text/javascript" src="js/jsAnim.js"></script>
<script type="text/javascript" src="js/main.js"></script>

Keep in mind to if you’d like the animations to begin when the page loads that you’ll need to create a function called init() and add the onload=”init()” into the beginning body tag. Next let’s create the onLoad function in our main.js file. From here we can initiate the jsAnimManager using this string:

var manager = new jsAnimManager();

After all the prep work you’ve put into getting the stage set and loading jsAnim, we can now begin to build our first simple Canvas animation:

object = document.getElementById("YourObject");
manager.registerPosition("YourObject");
object.setPosition(-250,25);

In this next line of code we’ll create our animated object:

var anim = manager.createAnimObject("YourObject");
anim.add({
     property: Prop.left, to:  new Pos(250, 25), duration: 2000
     });

With jsAnim the power is in the positioning system which you can animate in horizontal and vertical at once. Now you can do a bit more than just animate from one point to another obviously. You can make the selected object follow a path or paths. In the anim.add property, you change the Prop.left into Prop.positionSemicircle(false). The resulting animation should move you object in a semi circle.

Combining animations to create a ‘set’ is also rather simple. We just need to create 2 separate variables, for the purpose of this tutorial and the use of the jsAnim library, we’ll name them anim1 and anim2. Let’s add these variables into our script and we’re going to add the dimension property as well:

object = document.getElementById("YourObject");
manager.registerPosition("YourObject");
object.setPosition(-250,25);

var anim1 = manager.createAnimObject("YourObject");
var anim2 = manager.createAnimObject("YourObject");

anim1.add({
     property: Prop.position, to:  new Pos(250, 85), duration: 2000
     });

anim2.add({
     property: Prop.position, to:  new Pos(125, 25), duration: 2000
     });

When adding in the dimension property, we’ll being to see the object start to scale up or down based on what we want. In the example here is scales for 800 milliseconds of our animation:

anim2.add({
     property: Prop.dimension, to:  new Dim(125, 25), duration: 800
     });

The resulting animation should take your object and move it from point A to point B then to point C. Toy around with the script for a bit. When you look at the basic animation we just created, you could use it in the example of a video for a repetitive motion of a character or bot. In the same context you can also use the wait property to pause for a set amount of time.

anim.add({ property: Prop.position, to:  new Pos(250, 85), duration: 2000 });

anim.add ({ property: Prop.wait, duration: 1300 });

anim.add({ property: Prop.position, to:  new Pos(125, 25), duration: 2000 });

In the above example our object moves from the left to right, waits 1300 milliseconds, then moves to it’s downward position. So you should be able to create a repetitive motion set and even include wait periods. So let’s say in the setting of our gamespace that once a background character finishes their cycle of movement they’ll trigger an event. In our script we can add the ‘onComplete’ part in our function, like so:

anim.add ({ property: Prop.position, to new (250, 85), duration: 2000, onComplete: function() {alert("You earned 50gil !")}})

For the people used to animating in Flash you know that easing adds that finishing touch to any animation. With the jsAnim library you can easily create your easings (pun intended). There are a number of easing actions, keep in mind that you’ll need to include the prefix of ‘jsAnimEase‘:

  • jsAnimEase.linear
  • jsAnimEase.parabolicNeg
  • jsAnimEase.parabolicPos
  • jsAnimEase.backout(0.4)
  • jsAnimEase.backin(0.4)
  • jsAnimEase.backout(0.6)
  • jsAnimEase.backin(0.6)
  • jsAnimEase.bounceParabolic
  • jsAnimEase.bounceLinear
  • jsAnimEase.bounceSmooth

The ease method goes exactly where we place the onComplete function in our string of code:

anim.add ({ property: Prop.position, to new (250, 85), duration: 2000, ease: jsAnimEase.bounceSmooth });

Viola! You’re now able to animate as you would in Flash, but it is all in web semantic HTML5 and JavaScript! I’m not saying jsAnim is the only library out there, take some time to look around and find a library that better suits your needs.

Conclusion

If you’ve enjoyed what you’ve read here, go back and read my previous article on Canvas in this series, named parts 1, 2, and 3.

Links to my previous articles can be found in the related articles section on the left of this page. With this chapter of out Canvas adventures coming to a close soon, there may only be one or two articles left. That isn’t to say that developers aren’t finding new things to do with canvas everyday, just that there isn’t that much for me to keep writing about Canvas forever.

On a side note, Adobe has been making strides to not make Flash obsolete, just to tone down its platform on the web with the introduction of Adobe Edge.

Edge provides a way to create keyframed animation similar to that of Flash and then export out as HTML/CSS/JS. As with any new software Edge has a way to go in the features department, but Adobe says they plan to make regular updates spread across their delivery system to help improve Edge. At the moment the animation is very limited and the interface reminds me of a mixture between Photoshop and After Effects. At the moment Adobe is offering a preview of Edge, check it out for yourself at http://labs.adobe.com/technologies/edge

Ball Pool by Mr. Doob

The Ball Pool Experiement by Mr. Doob

By Joshua Rapp
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.
Home XML WordPress Web Services Web Development Web Design Underscore Uncategorized Tutorial Tools SQL Server Social Apps Snippet SEO Security RoR Responsive Design Resources Python PHP News MySQL Mobile Miscellaneous jQuery JavaScript Java J2EE HTML5 HTML Design Patterns