Using EaselJS to display a bitmap and create some effects

Post to Twitter

I written about EaselJS before and today I’m going to show another simple way to use the new Easel JavaScript library to interact with the HTML5 Canvas element (also I’m using JQuery). In particular I’ll show you how to use the Bitmap class to display an image and when you click on it we can do a couple effects.


The concept is simple: Display an image (in this case I used a JPEG) and then when the user clicks on it rotate the image and decrease the transparency.

The code:

<!DOCTYPE html>
<html lang="en-us" >
	<head>
	    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	    <title>EaselJS: Bitmap</title>
	    <script src="http://code.jquery.com/jquery-1.5.min.js"></script>
	    <script src="easel.js"></script>
		
		<script type="text/javascript">
			var img;
			
			$(function() {
				img = new Image();
				img.src = "gfs.jpg";
				
				$(img).load(function(){
					drawBitmap();
				});
			});
			
			function drawBitmap()
			{
				var stage = new Stage($("#mainCanvas").get(0));
				
				var bitmap = new Bitmap(img);
				stage.addChild(bitmap);

				bitmap.x = 190;
				bitmap.y = 110;
				
				stage.update();

				bitmap.onClick = function(event) {
					bitmap.rotation = 35;
					bitmap.alpha = 0.5;
					stage.update();	
				}
			}
		</script>
		<style>
		  #mainCanvas
		  {
			background-color: #222;
			border: solid 1px #0F0;
		  }
		  body
		  {
			background: #000;
		  }
		</style>
	</head>
	<body>
		<canvas id="mainCanvas" width="450" height="350">Canvas is not supported</canvas>
	</body>
</html>

Note: Substitute the paths for your location to Easel.js file as well as the image.

The code is pretty simple and you can see how easy EaselJS makes it to rotate and set the transparency of the image. I don’t know if you’ve ever tried to rotate an image using just JavaScript with the canvas but its not as easy as this.

The Results:

Post to Twitter

This entry was posted in HTML5, JavaScript. Bookmark the permalink.