logo
468x60-2-495


  • Home
  • Privacy Policy
  • About
search
Mar 30, 2012 Posted on Mar 30, 2012 in Hints and Tips | 10 comments

Animating Game Menus and Screen Transitions in HTML5: A Guide for Flash Developers

HTML5 and Flash development may have a lot in common, but as a Flash developer I’ve still found it to be a monumental task to re-learn my old skills in HTML5. In this tutorial, I’ll show you how I created an animated menu and screen transition for an HTML5 shoot-’em-up game.


Final Result Preview

Take a look at the result we’ll be working towards:

The Menu We Will Be Working Towards
Click to try the demo

Note the scrolling background, the ships that appear and rotate either side of each menu item, and the way the screen fades to black when you select an option.


Introduction

HTML5 and JavaScript are similar to ActionScript in many ways; there’s a lot of overlap in syntax, event listeners and methods. However there are some very distinct differences that I will cover in this tutorial:

  • Drawing Shapes
  • Drawing Images
  • Using Intervals
  • Animating
  • Mouse Events
  • Adding Support For Multiple Browsers

Something to note is that this tutorial mainly uses images which can be downloaded with the source or you may use your own images if you please (you will need to know the widths and heights).


Step 1: Setting Up

The first thing we will need to do is add the <canvas> element inside the body of an HTML file, so create one called ShootEmUp.html and insert the following:

<!DOCTYPE html>
<html>
	<head>
		<title>Shoot 'Em Up</title>
	</head>
	<body>
		<canvas id="myCanvas" width="480" height="320">
			<p>Your browser does not support HTML5!</p>
		</canvas>
	</body>

</html>

The highlighted lines insert the canvas element, which will render our actual menu. See this tutorial for a guide to canvas from scratch.

It’s already almost time to begin coding JavaScript! We have two options as to where the code can go; It can be written inside the HTML within <script> tags or it can be written in an external file. To keep things simple I will write all the code below the <canvas> element. But feel free to use an external file if you prefer; just remember to source it in.

<script type="text/javascript">
// Javascript Goes Here
</script>

Our next step will be to create four variables to reference the canvas element easily.

var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var width = canvas.getAttribute('width');
var height = canvas.getAttribute('height');

We first referenced the myCanvas variable and set it to point to the HTML canvas element. Another variable named context was created to get the canvas dimensionality (2D). Similar to Flash we are creating the final two variables, width and height, to simplify the process of accessing the canvas’s width and height properties.


Step 2: Loading and Drawing Images

Like in ActionScript we are going to create instances of our images.

var bgImage = new Image();
var logoImage = new Image();
var playImage = new Image();
var instructImage = new Image();
var settingsImage = new Image();
var creditsImage = new Image();
var shipImage = new Image();

We are missing a crucial piece of code for each instance – the source path! I saved all the images in the folder ‘Images’ within the same directory as the HTML file, so:

shipImage.src = "Images/ship.png";
bgImage.src = "Images/Background.png";
logoImage.src = "Images/logo.png";
playImage.src = "Images/play.png";
instructImage.src = "Images/instructions.png";
settingsImage.src = "Images/settings.png";
creditsImage.src = "Images/credits.png";

Before we draw the images to the canvas let’s create four arrays to hold the positions and sizes of the buttons (playImage, instructImage, settingsImage, creditsImage). These arrays will be used later to create a mouse over function.

var buttonX = [192,110,149,160];
var buttonY = [100,140,180,220];
var buttonWidth = [96,260,182,160];
var buttonHeight = [40,40,40,40];

Now we can draw the images to the canvas; this can be done within an onload function for each image, but an onload function does not need to be included – we can simply use drawImage().

bgImage.onload = function(){
	context.drawImage(bgImage, 0, 0);
};
logoImage.onload = function(){
	context.drawImage(logoImage, 50, -10);
}
playImage.onload = function(){
	context.drawImage(playImage, buttonX[0], buttonY[0]);
}
instructImage.onload = function(){
	context.drawImage(instructImage, buttonX[1], buttonY[1]);
}
settingsImage.onload = function(){
	context.drawImage(settingsImage, buttonX[2], buttonY[2]);
}
creditsImage.onload = function(){
	context.drawImage(creditsImage, buttonX[3], buttonY[3]);
}

If tested now, you should see a static image of a menu which we will soon breathe life into. The ship was not drawn in with the rest of the images because we are going to draw it later in a mouse event. By the way, if you haven’t been doing this so far, keep your variables grouped together at the top and do the same with functions.


Step 3: Animating Through Intervals

JavaScript lacks an onEnterFrame() equivalent, but we can easily create our own through the use of an interval (timer).

var frames = 30;
var timerId = 0;

timerId = setInterval(update, 1000/frames);

You may be confused as to how the interval is working so I will explain in brief. The interval is calling the function update() every (1000/frames) milliseconds to create a smooth refresh rate. The value of frames controls the fps; if frames is 25 then the browser will attempt to call update() every (1000/25=) 40 milliseconds.

Our next obvious step is to create the function update()

function update() {
	clear();
	move();
	draw();
}

Three more functions were just called. clear() is used to clear the canvas because unlike flash the canvas works like putting stickers on a board; the images can’t be moved after they have been placed. The next function, move(), is used for changing the variable values that are used with the images. Finally draw() is called to place those “stickers”.

funcion clear(){
	context.clearRect(0, 0, width, height);
}

Put simply, this code clears everything within the rectangle that is the size of the canvas and is drawn from (0,0), the top-left corner. That means it clears the entire visible canvas.

Before we move onto the next function, two variables should be introduced. backgroundY will be the variable for the background image’s y-position and speed will be used to subtract from backgroundY each update cycle.

var backgroundY = 0;
var speed = 1;

The effect that we are going to produce is a continuously scrolling background. The image is made up of two identical starfield images, one above the other, in a larger image (the image being twice the height of the canvas). We will slowly move the image up until the second half is completely in view and then we will reset the position of the image back to the first half.

function move(){
	backgroundY -= speed;
	if(backgroundY == -1 * height){
		backgroundY = 0;
	}
}

Finally we have the draw() function. All of the images will be redrawn, but one change to notice is that the bgImage‘s y value has been replaced with the variable backgroundY.

context.drawImage(bgImage, 0, backgroundY);
context.drawImage(logoImage, 50,-10);
context.drawImage(playImage, buttonX[0], buttonY[0]);
context.drawImage(instructImage, buttonX[1], buttonY[1]);
context.drawImage(settingsImage, buttonX[2], buttonY[2]);
context.drawImage(creditsImage, buttonX[3], buttonY[3]);

Test now and admire the smooth scrolling background.


Step 4: Checking the Mouse Position

One thing the HTML5 <canvas> is missing is support for image event listeners, meaning we can’t simply write playImage.mouseover = function(){}. Instead, we have to get the postion of the mouse relative to the canvas and figure out whether it is over an object.

var mouseX;
var mouseY;

canvas.addEventListener("mousemove", checkPos);

The two variables introduced are going to be used to get the current postion of the mouse. We added an event listener, like in ActionScript, that calls the function checkPos() every time the mouse moves.

function checkPos(mouseEvent){
	mouseX = mouseEvent.pageX - this.offsetLeft;
	mouseY = mouseEvent.pageY - this.offsetTop;
}

If you alerted the values of mouseX and mouseY every time you moved the mouse you would get the correct position. But there is one problem: not all of the modern desktop browsers support this method. To overcome this problem we can use the little hack instead:

if(mouseEvent.pageX || mouseEvent.pageY == 0){
	mouseX = mouseEvent.pageX - this.offsetLeft;
	mouseY = mouseEvent.pageY - this.offsetTop;
}else if(mouseEvent.offsetX || mouseEvent.offsetY == 0){
	mouseX = mouseEvent.offsetX;
	mouseY = mouseEvent.offsetY;
}

This checks whether the browser uses “page” or “offset” properties to return the position of the mouse, and adjusts the values (if necessary) to get the mouse position relative to the canvas.

Now remember that ship we instanced, but didn’t draw? We are going to take that static image, spin it and make it appear whenever we mouse over the buttons!

var shipX = [0,0];
var shipY = [0,0];
var shipWidth = 35;
var shipHeight = 40;

var shipVisible = false;
var shipSize = shipWidth;
var shipRotate = 0;

The first four variables are the same as before (we have two positions because there will be two ships). The shipVisible variable will be set true when the mouse is over a button. As for shipSize and shipRotate, they will be used to scale the ship vertically and reposition it to give the illusion that it is spinning. Keep in mind that images scale right to left.

for(i = 0; i < buttonX.length; i++){
	if(mouseX > buttonX[i] && mouseX < buttonX[i] + buttonWidth[i]){
		if(mouseY > buttonY[i] && mouseY < buttonY[i] + buttonHeight[i]){

		}
	}else{

	}
}

Add the code in the checkPos() function. First we cycle through the buttons there are (I figured out the value using buttonX.length). Next we compare the mouseX to see whether it is greater than the current button’s buttonX and less than its buttonX + buttonWidth – i.e. within the horizontal bounds of the button. We then repeat the process in another if statement for the Y values. If this is all true, then the mouse must be over a button, so set shipVisible to true:

shipVisible = true;

And within the empty else statement set it to false; it will then be called whenever you mouse out of a button:

shipVisible = false;

Under shipVisible = true we will set the initial values for the shipX and shipY, and perform all of the scaling within the move and draw functions.

shipX[0] = buttonX[i] - (shipWidth/2) - 2;
shipY[0] = buttonY[i] + 2;
shipX[1] = buttonX[i] + buttonWidth[i] + (shipWidth/2);
shipY[1] = buttonY[i] + 2;

For the first shipX, which we want just to the left of the button, we set the value to (the current button’s X – half of the ship width), and I moved it over 2 pixels to the left to make it look better. A similar process is repeated for the first shipY. For the second shipX we position at the (current button’s X + that button’s width + half the ship width), and then we set the Y like before.

The tricky part comes now. We have to scale the ship and move it over to compensate for the scaling. Within the move() function write this if statement.

if(shipSize == shipWidth){
	shipRotate = -1;
}
if(shipSize == 0){
	shipRotate = 1;
}
shipSize += shipRotate;

The code begins subtracting the value of shipSize, which will be used to scale the image when we draw it; once it reaches zero the process reverses until it is full scale again.

Now we can move into the draw() function. Below all of the other draw methods add the following if statement.

if(shipVisible == true){
	context.drawImage(shipImage, shipX[0] - (shipSize/2), shipY[0], shipSize, shipHeight);
	context.drawImage(shipImage, shipX[1] - (shipSize/2), shipY[1], shipSize, shipHeight);
}

The ships are being drawn normally with the exception of the X positions being compensated by subtracting half of the current scale.


Step 5: Checking for Mouse Clicks

Add another event listener for mouseup and create a new variable for a second interval we will create.

var fadeId = 0;
canvas.addEventListener("mouseup", checkClick);

Create the function checkClick().

function checkClick(mouseEvent){
	for(i = 0; i < buttonX.length; i++){
		if(mouseX > buttonX[i] && mouseX < buttonX[i] + buttonWidth[i]){
			if(mouseY > buttonY[i] && mouseY < buttonY[i] + buttonHeight[i]){

			}
		}
	}
}

Like before, we check whether the position of the mouse is correct. Now we need to create the new interval, and stop the other interval and event listeners.

fadeId = setInterval("fadeOut()", 1000/frames);
clearInterval(timerId);
canvas.removeEventListener("mousemove", checkPos);
canvas.removeEventListener("mouseup", checkClick);

Nothing new here except that we need to create a function called fadeOut(). We also need to create another variable called time.

var time = 0.0;
function fadeOut(){
	context.fillStyle = "rgba(0,0,0, 0.2)";
	context.fillRect (0, 0, width, height);
	time += 0.1;
	if(time >= 2){
		clearInterval(fadeId);
		time = 0;
		timerId = setInterval("update()", 1000/frames);
		canvas.addEventListener("mousemove", checkPos);
		canvas.addEventListener("mouseup", checkClick);
	}
}

It has some new methods, but it’s quite simple. Since we stopped all of the event listeners and the other interval our menu is completely static. So we are repeatively drawing a transparent black rectangle on top of the menu – without clearing it – to give the illusion of fading out.

The variable time is increased every time the function is called and once it reaches a certain value (once 20 “frames” have passed, in this case) we clear the current interval. Here I reset the menu, but this is where you would draw a new section of the menu.

One last thing to note is that when you draw shapes on the canvas the fillStyle is set with a rgb (red, green, blue) value. When you want to draw transparent shapes, you use rgba (red,green,blue,alpha).

I hope that’s demystified a bit of the learning process for switching from simple AS3 programming to simple canvas programming. Post a comment if you have any questions!



View full post on Activetuts+

Mar 28, 2012 Posted on Mar 28, 2012 in Hints and Tips | 10 comments

How to Create an HTML5 Hangman Game With Canvas: Tuts+ Premium

This week, we’ve got a two-part Premium tutorial, detailing how to create an HTML5 Hangman game using the HTML5 canvas. You’ll learn how to draw directly to the canvas (both simple shapes and animations using a stylesheet), how to play audio in a way that works on all modern browsers, how to use Local Storage to keep scores that persist even when the browser is closed, and how to implement both keyboard and mouse controls.


Premium Preview

Let’s take a look at the final result we will be working towards:

HTML5 Hangman game tutorial
Click to play the demo.

It’s easy to change any aspect of the game. Want to draw the hangman differently? You can tweak the drawing functions, or copy individual body parts from a separate image sprite sheet. Want different music or animation? No problem, just replace the files. Want to give the player more (or fewer) chances per word, to alter the difficulty? That’s easy too. And of course you can change the list of words.

Every concept and each line of code is explained, so you’re not just learning how to create a Hangman game – you’re learning how to code in JavaScript with the HTML5 APIs.


Read the Full Tutorial

Premium members can access the full two-part tutorial right away!

  • The Basic Gameplay
  • Bells and Whistles
  • If you’re not yet a Premium member, you can still read the first few steps of each part, using the links above.


    Tuts+ Premium Membership

    We run a Premium membership system which periodically gives members access to extra tutorials, like this one, from across the whole Tuts+ network. If you’re a Premium member, you can log in and read the tutorial. If you’re not a member, you can of course join today!

    Also, don’t forget to follow @envatoactive on twitter, circle us on Google+, like us on Facebook, and grab the Activetuts+ RSS Feed to stay up to date with the latest tutorials and articles.



    View full post on Activetuts+

Mar 25, 2012 Posted on Mar 25, 2012 in Hints and Tips | 10 comments

Build an Image Editor With EaselJS, jQuery, and the HTML5 File API – Tuts+ Premium

In this Premium tutorial, using the HTML5 Canvas and File APIs, we’ll create a full-blown picture editor, with features on par with some desktop applications – including simple transformations like skewing and rotating, and more complicated filters like Gaussian blurring, embossing, and edge detection. For this, we will use the EaselJS library and jQuery.


Premium Preview

Let’s take a look at the final result we will be working towards:

HTML5 EaselJS jQuery Image Editor
Click to try the demo.

Note the huge set of features:

  • Ability to load and save image files from and to your hard drive
  • Built-in print capability (that doesn’t print the UI elements)
  • Undo/redo memory
  • Multiple layers, including text layers
  • Simple transformations: scale, rotate, skew, flip
  • Complex filters: brightness, colorify, blur, emboss, sharpen, and more
  • Basic scripting capabilities

…all coded in JavaScript, using jQuery, HTML5, and EaselJS.

Rather than explaining how to build this app line-by-line from scratch, the tutorial starts from the finished source code and explains how each section works, as well as the theory behind concepts such as the Gaussian blur filter. The full source code is also available to download and modify.


Read the Full Tutorial

Premium members can access the full tutorial right away!

If you’re not yet a Premium member, you can still read the first few steps for free.


Tuts+ Premium Membership

We run a Premium membership system which periodically gives members access to extra tutorials, like this one, from across the whole Tuts+ network. If you’re a Premium member, you can log in and read the tutorial. If you’re not a member, you can of course join today!

Also, don’t forget to follow @envatoactive on twitter, circle us on Google+, like us on Facebook, and grab the Activetuts+ RSS Feed to stay up to date with the latest tutorials and articles.



View full post on Activetuts+

Mar 9, 2012 Posted on Mar 9, 2012 in Hints and Tips | 10 comments

oCanvas: A jQuery- and Flash-Style Library for HTML5 Canvas

With the advent of tools like Adobe Edge and libraries like EaselJS, more resources are becoming available for developers looking to create interactive HTML5 content. Many of these tools are being geared specifically for Flash developers to make the transition from ActionScript to HTML5 canvas a smooth one. This article will overview oCanvas, an HTML5 library that developers might not only find invaluable but also very easy to use.


HTML5 Canvas Background

Before we dive into exploring oCanvas, let’s quickly set the scene for how HTML5 canvas works. If you want a more thorough explanation on how to use HTML5 canvas, check out this tutorial.

If you know ActionScript, you already know a lot of JavaScript, which is where the real power resides when working with canvas. We use the HTML5 drawing API to create our content along with some good ol’ JavaScript to make things interactive and dynamic. But when we combine the two, the approach behind how we go about putting together our code is a bit different than what we are used to with ActionScript.

In short, to use the native Canvas API, we draw pixels onto the drawing context of the canvas. But the key thing to remember is that we are working with the entire canvas, not just a single shape or image that we have drawn. Every time we want to alter something we have drawn we have to redraw the entire canvas. If we want to animate something we have to redraw the canvas over and over in our JavaScript to make it appear that things are moving.

This notion is very similar to traditional animation, where animators had to draw each and every pose in their sequence and have the camera move through them very quickly to simulate movement. But if you’re used to tree-like structures such as the DOM, or the display list in Actionscript, this notion can be hard to get your head around. This rinse and repeat approach to programming is much different than working with objects for most developers.


Introducing oCanvas

Luckily for those of us who are so accustomed to working with objects, oCanvas brings that familiar approach to HTML5 canvas. oCanvas is a JavaScript library developed by Johannes Koggdal with the intention of making it easier to develop with HTML5 canvas. It allows you to work directly with objects, modify their properties and hook up events to them all while handling the nitty-gritty behind the scenes stuff for you. As put best by Johannes on his blog:

My goal has always been to make it really easy for people to build canvas things based on objects. I decided on the name oCanvas as a contraction of “object canvas”.


Get the Library

Download oCanvas

To start using oCanvas we need to include a copy of the library on our HTML page. We can either reference the CDN-hosted file, or host a local copy ourselves. Jump over to the oCanvas website and you can either download a copy of the library or grab the reference to the CDN-hosted version. The current version is 2.0 and was released only a few weeks ago, which addressed many of the bugs that were in the initial release. On the site there is a minified production version, which is good to use when you’re ready to deploy your project. There is also a development version, which is uncompressed but is better for debugging. I like to directly link to the hosted version for faster loading and caching by the browser.

<script src="http://cdnjs.cloudflare.com/ajax/libs/ocanvas/2.0.0/ocanvas.min.js"></script>

Initial Code Setup

After you make a reference to oCanvas, next we need to setup a canvas element in the body of our HTML and create a reference to it for use in our Javascript.

<canvas id="canvas" width="800" height="600"></canvas>

As always, if you place your script above the canvas element, you need to wrap it in a function so you know the DOM is ready. There’s a couple ways to go here. You can either create your own function and then call it in your body element when it loads, like this:

function Main()	{
	// your oCanvas code
}

<body onload="Main();">

Or you can wrap your code within oCanvas’s built-in domReady() method. This is the equivalent to jQuery’s $(document).ready(). In oCanvas we use this:

oCanvas.domReady(function () {
	//Your Code Here
});

Note: You could use jQuery’s $(document).ready() method if you wanted to.


Initialize an Instance of oCanvas

This piece of code is absolutely necessary and is the first thing you must write when using oCanvas.

var canvas = oCanvas.create({
	canvas: "#canvas",
	background: "#0cc",
	fps: 60
});

In this code we store a reference to the canvas element within our document and get access to the core instance, which will enable you to start creating objects. The create() method takes an object as its argument which controls how oCanvas will work. There are numerous properties to pass into the create() method, but the only mandatory one is the canvas property: a CSS selector that must point to a canvas element within the DOM.

The other properties passed in the above code are the background and fps properties. The background property allows you to apply a background to the canvas, which can be CSS color values, gradients and images. If it’s omitted, the canvas will be transparent. The fps property sets the number of frames per second any animation will run at. The default is 30 fps.

Note: While we overview many of the features in oCanvas, I recommend checking out the library’s documentation to get a better understanding of each section.


Display Objects

Display Objects

There are numerous types of display objects you can create with oCanvas. You can create shapes such as rectangles, ellipses, polygons and lines along with images, text and even sprite sheets. To create a new display object we use oCanvas’s Display Module, and specify what kind of display object we want to create as well as some basic properties – like so:

var box  = canvas.display.rectangle({
	x: 50,
	y: 150,
	width: 50,
	height: 50,
	fill: "#000"
});

Then to add it to the display we call a familiar method for you Flash developers…

Good Ol’ addChild()

Yes an oldie but a goodie, which makes adding objects to oCanvas a familiar process. So to add our box to the canvas, we would write:

canvas.addChild(box);

Just like in ActionScript, addChild() adds the specified object as a child of the caller. And in turn the child’s x and y will be relative to its parent. So in this case we are making box a child of the canvas, which we could simplify like this:

box.add();

The add() method also adds the object to the canvas — which is really the same thing as canvas.addChild(box). But addChild() is most useful for adding an object as a child to an already created display object, like:

var square  = canvas.display.rectangle({ x: 0, y: 0, width: 10, height: 10, fill: "#990000"});
box.addChild(square);

Let’s take a look at some of the different types of display objects you can create in oCanvas.

Shapes

You already saw a square, but we can use the rectangle display object to create a lot of things. Here’s a rectangle with a blue stroke:

var rectangle = canvas.display.rectangle({
	x: 500,
	y: 100,
	width: 100,
	height: 200,
	fill: "#000",
	stroke:"outside 2px blue"
});

The fill property can take any valid CSS color, along with CSS gradients and even image patterns.

To create an ellipse we would write:

var ellipse = canvas.display.ellipse({
	x: 100,
	y: 100,
	radius_x: 20,
	radius_y: 30,
	fill: "rgba(255, 0, 0, 0.5)"
});

If you want a full circle, just replace the radius_x and radius_y properties with a single radius property.

Creating any kind of regular polygon is just as easy — all you have to do is specify the number of sides and the radius you want your shape to have. To create a triangle:

var triangle = canvas.display.polygon({
	x: 320,
	y: 145,
	sides: 3,
	radius: 50,
	fill: "#406618"
});

How about a pentagon?

var pentagon = canvas.display.polygon({
	x: 200,
	y: 50,
	sides: 5,
	rotation: 270,
	radius: 40,
	fill: "#790000"
});

To accomplish that with the HTML5 canvas API, you would have to draw a bunch of paths and try figure out what x and y positions to join them at. I attempted to draw an octagon for comparison’s sake but as you can see below I gave up quite easily. Not quite sure what this is supposed to be.

var canvas = $("#canvas");
var ctx = canvas.get(0).getContext("2d");
ctx.fillStyle = '#000';
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(100,50);
ctx.lineTo(50, 100);
ctx.lineTo(0, 90);
ctx.closePath();
ctx.fill();

Images

Creating display objects with images doesn’t get any simpler than in oCanvas. Just specify an x and y position and the path to the image file:

var tree = canvas.display.image({
	x: 100,
	y: 350,
	image: "tree.png"
});

A nice feature of the image display object is the tile property, which lets you easily create a grid of the same image instead of drawing it over and over.

Text

oCanvas contains a text display object and handles font styling just like CSS does.

var text = canvas.display.text({
	x: 70,
	y: 300,
	align: "center",
	font: "bold 18px sans-serif",
	text: "oCanvas Rocks",
	fill: "purple"
});

You can use many of the other text properties you’re familiar with from CSS. Check out the documentation on text for more.


Properties and Methods

All display objects inherit a common group of properties and methods. Some of the most common display object properties are: x, y, width, height, rotation, scalingX, scalingY, opacity, shadow (uses CSS-box-shadow syntax) and zIndex. You can check out this link for a full list of the base properties and methods. Let’s take a look at some other noteworthy ones.

Origin

This method is a big time-saver because it let’s you easily set the origin inside the object. In other words, it allows you to set the registration point of the object. If you ever tried to perform a rotation from the center with the HTML5 Canvas API, you know how big of a headache it can be. You have to do a slew of actions of saving the drawing state, translating the canvas, performing your rotation and then restoring the drawing state. With the origin property you can easily define an object’s origin:

var obj  = canvas.display.image({
	x: 270,
	y: 270,
	origin: {
		x: "center",
		y: "center"
	}
});

This would draw the image from its center; if we were to rotate the object, it would rotate from its center, too. Besides “center” you could also pass in “left” or “right” for the x and “top” or “bottom” for the y positions. In addition to using the predefined keywords, you could also supply positive or negative numbers as values of where to draw the object. The default origin for all display objects is defined at its top left.

You can also use the setOrigin() method at any time to define an object’s origin:

obj.setOrigin("left", "bottom")

ID

A display object’s id, which is really a read-only property, corresponds to where the object exists in the draw list — which you can think of as the display list. I find it to be very useful because it can serve as a unique identifier in certain situations when you might be seeking out a specific object in your code. Consider a basic snippet like this:

getId(box.id)
function getId(id) {
	if (id==9) console.log("CORRECT ! " + id)
	else console.log("WRONG! " + id)
}

Composition

The composition property is the equivalent of globalCompositeOperation within the native Canvas API. If you’re not familiar with it, it basically determines how pixels are rendered when drawn onto already existing pixels on the canvas. I encourage you to read up on the different compositing operations you can set, but with oCanvas you can simply set the operation you want by passing it as a string:

var shape  = canvas.display.rectangle({
	x: 270,
	y: 270,
	width: 180,
	height: 80,
	fill: "#ff6900",
	composition:"destination-atop"
});

There are many different operations you can pass in but I think one of the neat things you can do with the composition property is create masks between different display objects. Check out the file named masks.html in the download package. If you ever relied on creating layer masks in your Flash applications, you’ll enjoy this one.

Methods of Note

Since we mentioned rotating objects earlier, you can quickly rotate an object with the rotate() and rotateTo() methods:

obj.rotate(45);

You can also simply set the rotation property:

obj.rotation=45;

There’s also the move() and moveTo() methods which, like their names suggest, allows you to move an object by a specified amount of pixels for the former and toa specified x and y position for the latter.

obj.moveTo(100, 100)

The same idea works for the scale() and scaleTo() methods():

obj.scale(1.25, 0.25)
obj.scaleTo(1.5, 1.5)

We mentioned addChild() before; let’s not forget about removeChild() and removeChildAt(). And like the add() method, we can do the opposite with remove().

Another really useful method is clone(), which allows you to duplicate a display object and all of its properties.

var box  = canvas.display.rectangle({ x: 50, y: 150, width: 50, height: 50, fill: "#000"});
var box2 = box.clone(x:200)

Events

A big plus to oCanvas is that you can add events to specific objects. The oCanvas contains many methods and properties for easily handling mouse, keyboard and even touch events all with one simple method.

Bind()

If you’re familiar with jQuery, you probably already know where I’m going with this.

canvas.bind("click tap", function () {
	canvas.background.set("#efefef");
});

All this does is change the background color of the canvas, but notice how we pass in “click tap” — easily allowing us to add support for both mouse and touch devices.

Besides click events, you can also listen for other mouse events:mousedown, mouseup, mousemove, mouseenter, mouseleave and dblclick.

A simple rollover effect might look like this:

box.bind("mouseenter", function () {
	canvas.background.set("#333");
}).bind("mouseleave", function () {
	canvas.background.set("#000");
});

This is an example of chaining functions — which (not to sound like a broken record) is another jQuery feature leveraged in oCanvas.

But instead of altering the canvas when a mouse event occurs, what about altering an actual display object? This is still HTML5 Canvas after all, so we must remember to call an important method to tell the canvas to update itself.

canvas.redraw()

The redraw() method (which is actually part of the Draw Module, not the Events Module) redraws the canvas with all the display objects that have been added. So if want to perform an action on a particular object and have the rest of the draw list stay intact, we must add this one simple line of code to our functions:

square.bind("click tap", function () {
	square.x+=50;
	canvas.redraw();
});

Unbind()

What good is an event listener if we can’t remove it?

rectangle.bind("click tap", function onClick ()
	{
		this.fill="#FF9933";
		canvas.redraw();
		rectangle.unbind("click tap", onClick)
	});

How About a Quick Drag and Drop?

We don’t need the bind() method for this one. We just write:

circle.dragAndDrop();

That’s probably the quickest and easiest drag and drop code you’ll ever write.

Note on events: When you’re working with events, it’s natural to want to get as much information as possible about the event. Luckily, we can still do so when working with oCanvas. For example if we take the click handler a few lines up and log the event to the console we can see all the properties we have from the event.

rectangle.bind("click tap", function onClick (e)
{
	this.fill="#FF9933";
	canvas.redraw();
	rectangle.unbind("click tap", onClick);
	console.log(e);
});
Firefox console log

Keyboard and Touch Events

Besides mouse events, oCanvas has entire modules dedicated to keyboard and touch events with their own unique methods and properties. These events are also handled with the bind() method. The events system in oCanvas is a very broad topic, so I encourage taking a look at the events section in the documentation and experimenting.


Timeline

With the Timeline Module we can set up our main loop for our application. If you were creating a game, this would essentially be your game loop. I like to think of it as the equivalent of an ENTER_FRAME in Flash.

It’s simple to set up — we just call the setLoop function and chain the start() method to it:

canvas.setLoop(function () {
	triangle.rotation+=5;
}).start();

If we wanted to tie the setLoop() function to an event – say to a mouse click – we could do something like this:

canvas.setLoop(function () {
	triangle.rotation+=5;
})

button.bind("click tap", function () {
	canvas.timeline.start()
});

And we could stop the timeline by simply calling:

canvas.timeline.stop();

Animation

Using setLoop() is the way to go for animations that will occur over a long period of time and to handle constant updates you have to make throughout your application. But oCanvas has built in methods to handle more simpler and basic animations that are commonly needed. These methods are also practically taken verbatim from jQuery.

Animate()

The animate() method works just like it does in jQuery. If you’re not familiar with this side of jQuery, think if it like a tweening engine like TweenMax or Tweener for Flash. You can animate any property that can be set by a numeric value:

circle.animate(
	{
		y: circle.y - 300,
		scalingX:.5,
		scalingY: .5
	},
	"short",
	"ease-in",
	function () {
		circle.fill = "#45931e";
		canvas.redraw();
	}
);

Here we animate the circle’s y position and overall size, apply some easing, and when it is finished we run a callback function that changes its fill color. But don’t forget to call redraw().

fadeIn(), fadeOut(), and fadeTo()

To fade an object in and out we could simply call:

square.fadeIn();
square.fadeOut();

To fade the opacity to a specific value, we’d use fadeTo():

square.fadeTo(.6);

You can also define the duration, easing and provide a callback function for these methods in the same way you would with the animate() method.


Scenes

oCanvas contains a very useful Scenes Module that allows you to easily separate your application into different states. Game developers might appreciate this one because it’s a simple approach to breaking down your game into different sections. Even old school Flash animators might liken the Scenes Module to the Scenes panel, which allows you to literally create different scenes within a Flash project.

To create a scene in oCanvas we call the create() method to return a scenes object:

var intro = canvas.scenes.create("intro", function () {
	// add display objects here
});

Within the create() method we pass in two arguments: the name of the scene as a string, and a function where we add the display object we want to add to that scene.

var introText = canvas.display.text({
	x: canvas.width / 2,
	y: canvas.height/2,
	align: "center",
	font: "bold 36px sans-serif",
	text: "Introduction",
	fill: "#133035"
});
var intro = canvas.scenes.create("intro", function () {
	this.add(introText);
});

Now we have to load our scene and those objects will be added to the display:

canvas.scenes.load("intro");

Notice we pass in the name we gave the scene when we created it.

And of course we can unload a scene at any time:

canvas.scenes.unload("intro");

Imagine how much of a time-saver this could be if you used scenes and event handlers together.


oCanvas vs. EaselJS

The only real downside to oCanvas is that it hasn’t gained as much traction in the development community as you might guess – or at least it seems that way for now. Part of that reason for this, I think, is because of the popularity of EaselJS. There seems to be alot more awareness and resources out there for EaselJS than there are for oCanvas — which is hard to believe since the latter was first released in March 2011, but for some reason it has flown under the radar.

I’ve been using both libraries for quite some time now, and I can honestly say I am big fan of both. EaselJS definitely feels more like you are using ActionScript and if you’re a Flash developer will be easy to pick up. And as we’ve seen, oCanvas could pass for jQuery’s long lost brother in many ways. So if you’re a pure ActionScripter, you might just naturally gravitate towards EaselJS— especially since Easel was written specifically to appeal to Flash developers.

However, I’ve been using Actionscript much longer than jQuery and I personally find oCanvas simpler to use and less verbose to write. And even though EaselJS is pretty easy to use itself, the simple syntax in oCanvas just makes it such a welcome tool.

But besides the simpler syntax, oCanvas and EaselJS in many ways are are pretty much interchangeable. Both libraries can accomplish more or less the same tasks and there’s very little difference in performance, if any. However I do notice the Ticker function in EaselJS runs a little more smoothly than oCanvas’ setLoop function (though that could just be a browser-based difference).

EaselJS does have much more of an extensive API — especially when it comes to drawing and effects. And if you take into account TweenJS and SoundJS, Easel is definitely a more complete tool — especially if you’re used to using an application like Flash that offers fine-tune control over your projects. But if you’re new to the whole HTML5 game, you’re likely to hit the ground running with oCanvas much faster. When I was first introduced to oCanvas, I found it so much fun to play with. Everything is already there for you — all the necessary methods and events to start creating, manipulating and animating objects right away.


Wrapping Up

Whichever library you prefer, oCanvas and EaselJS are only the beginning of what I think will be an influx of tools and resources to allow developers to easily create browser-based applications. The features of oCanvas detailed in this article barely scratch the surface of what could be created using this very powerful library.

By no means though is oCanvas (or any library for that matter) a reason not to learn and use the native HTML5 Canvas API. But if you find yourself in a situation where all your former Flash clients are now looking for you to create HTML5 apps (like mine were) and you don’t have time to learn something like the unfriendly transformation matrix in the native Canvas API — oCanvas can definitely ease the learning curve.



View full post on Activetuts+

Feb 11, 2012 Posted on Feb 11, 2012 in Hints and Tips | 10 comments

Build an HTML5 MP3 Player With SoundManager 2 – Tuts+ Premium

It’s time for another Premium tutorial! This week, James Tyner will walk you through the process of building an HTML5 MP3 player, step by step, with the SoundManager 2 library, jQuery, and a little help from Flash (for extra audio functionality).


Premium Preview

SoundManager 2 HTML5 MP3 Player tutorial
Click for a demo.

In this tutorial I will show you how to create a JavaScript MP3 Player with jQuery and the SoundManager 2 JavaScript library that uses a hidden SWF file to play the sounds. (I could have used HTML5 Audio, but we would have lost the ID3 functionality, and so would have had to hard-code all of our artists and titles.)

You’ll use jQuery, jQuery UI, and jScroller to manage the UI, with graphics already provided for you, and learn how to use SoundManager 2, a cross-browser JavaScript audio library that even works on iOS (if you are willing to lose the extra features, such as ID3 functionality).

Everything is explained step by step as you build the player. Check out the demo to see the end result.


Read the Full Tutorial

Premium members can access the full tutorial right away!

If you’re not yet a Premium member, you can still read the first few steps of the tutorial, which are enough to help you code the basic play and stop buttons..


Tuts+ Premium Membership

We run a Premium membership system which periodically gives members access to extra tutorials, like this one! You’ll also get access to Psd Premium, Vector Premium, Audio Premium, Net Premium, Ae Premium, Cg Premium, Photo Premium, and the new Mobile Premium too. If you’re a Premium member, you can log in and download the tutorial. If you’re not a member, you can of course join today!

Also, don’t forget to follow @envatoactive on twitter, circle us on Google+, like us on Facebook, and grab the Activetuts+ RSS Feed to stay up to date with the latest tutorials and articles.



View full post on Activetuts+

Page 1 of 41234»
search search search search search
Find an Article
Categories
  • Flash Video Training
  • Hints and Tips
  • Recommended
Please Support Our Sponsors
Recent Posts
  • The Math and ActionScript of Curves: Drawing Quadratic and Cubic Curves
  • Weekend Lecture: Understanding Games, a Flash Game About Game Design
  • Weekend Lecture: Understanding Games, a Flash Game About Game Design
  • Workshop Coding Challenge: Fix This Breakout Game
  • Enable the Latest AIR SDK in Flash Professional CS5.5+
Tag Cloud
2011 ActionScript Active Activetuts+ Adobe animation Basic Basix Best Build Button Character Create Creating Critique Custom design Effect Effects Files Flash from Game Guide HTML5 Introduction Macromedia Motion Muzzle part Player Premium Professional Quick Silverlight Simple Text Tool Tutorial Tuts+ Tween Using Video website Workshop
About Our Site:

Hey there and welcome to "Flash Video Training Source", a resource for anybody interested in learning more about Adobe's great tool. We feature educational videos, which will help you master Adobe Flash and help you get to know all of its features. We at "Flash Video Training Source" believe that video training and video... more

Why don't you follow us on Twitter and get the latest video tutorials twitted to your account. Just click on the floating twitter bar to your right!

Go Back In Time
May 2012
M T W T F S S
« Apr    
 123456
78910111213
14151617181920
21222324252627
28293031  
Pretty Blank Box
top

Blogroll

  • Development Blog
  • Documentation
  • Plugins
  • Suggest Ideas
  • Support Forum
  • Themes
  • WordPress Planet

Meta

  • Log in
  • Entries RSS
  • Comments RSS
  • WordPress.org

Archives

  • May 2012
  • April 2012
  • March 2012
  • February 2012
  • January 2012
  • December 2011
  • November 2011
  • October 2011
  • September 2011
  • August 2011
  • July 2011
  • June 2011
  • May 2011
  • April 2011
  • March 2011
  • February 2011
  • January 2011
  • December 2010
  • November 2010
  • October 2010
  • September 2010
  • August 2010
  • July 2010
  • June 2010
  • May 2010
  • April 2010
Powered by WordPress  |  Designed by Elegant Themes  |  Lightning Fast Hosting by Site 5 Hosting