drawkcaB | Backward Compatible logo

rants and tips about software

Creating a mouse hover effect for button/image with HTML5 Canvas and easel.js

After ditching many other HTML5 Canvas libs, I was left with Easel.js. Documentation is sparse, without many examples. I had to google a lot to find this information, so I'm getting it up here hoping it might help someone else as well.

If you need a simple graphic (or text) button with hover support, then Easel's ButtonHelper class is what you need. You can create a simple image containing 3 buttons states (normal, hover, pressed) and set up ButtonHelper to do all the work.

Here's how I did it. First create an image with all 3 states. I used this PNG:

As you can see my image is 300x45 with each state being 100x45 pixels. Now the code:

// setup
stage.enableMouseOver();
var data = {
     images: ["3buttons.png"],
     frames: {width:100, height:45},
     animations: {normal:[0], hover:[1], clicked:[2]}
};
var spriteSheet = new createjs.SpriteSheet(data);
var button = new createjs.BitmapAnimation(spriteSheet);
var helper = new createjs.ButtonHelper(button, "normal", "hover", "clicked");

// set the button coordinates and display it on the screen
button.x = 100;
button.y = 100;
button.gotoAndStop("normal");
        

Yes, that's all. If you're looking for example with Text, take a look at this jsFiddle.

Note that each of the button states can be animated, just add more frames to the image file and configure the data.animations properly.

Milan Babuškov, 2013-05-08
Copyright © Milan Babu┼íkov 2006-2017