logo
468x60-2-495


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

Flash CS6: What’s New?

The newest Adobe Creative Suite has been announced. It’ll be available to purchase on May 7th; let’s take a look at what’s new for Flash app and game developers.


What’s New in Flash Professional CS6?

Most of the big new features in the flagship Flash software do not involve Flash Player at all; the one exception seems to be integration with Starling, the Stage3D library for 2D assets which we’ve covered before. Other than that, the emphasis is on mobile and HTML5 development.

A new mobile simulator lets you emulate tilting and rotating a phone (affecting the acceleromoter and the screen orientation), as well as touch gestures such as pinch-to-zoom. There are also new debugging features. I’ll let Mobiletuts+ go into more detail on these additions!

Flash Pro CS6 also has the ability to export to the HTML5 library CreateJS, which we’ve also covered before under the name EaselJS. No, this doesn’t mean you can take an existing Flash app or game and create an HTML5 canvas version, but you can export animations, images, and sounds, both from the stage and from the library, into clean JavaScript format.

Along similar lines, movie clips can also be exported to sprite sheets, which will be useful for game development in both HTML5 and Flash Player (as well as pretty much any other platform, for that matter).


What About Flash Builder and Flash Catalyst?

Flash Builder is not a “Creative Suite” product – it doesn’t have the CS name – so it runs on a different upgrade schedule. This means it’s not going to be updated to coincide with the CS6 launch. It has been dropped from the Web Premium suite, however, since the Web Premium suite no longer exists (it’s been combined with Design Premium to form Web and Design Premium), but it’s still available in the Master Collection.

Flash Catalyst, on the other hand, has been dropped; there will not be a Flash Catalyst CS6.


Creative Cloud

CS6 in general also sees the launch of the Adobe Creative Cloud; in brief, this allows you to pay an ongoing subscription fee to get every single CS6 app. For some people, this will be a much more attractive or convenient option than buying the entire Suite as a set of software – especially as there’s no additional fee to get future updates.


What Do You Think?

Personally, I think it’s interesting (but not at all surprising) that CS6 does not have much to offer programmers. I feel that’s been the case with Flash Professional for a while now; the Flash Platform and AS3 are not constrained to the 18- or 12-month Creative Suite release schedule, and FlashDevelop, Flash Builder and FDT are far better tools for coding anyway. (With that in mind, I am surprised that Flash Builder is not included in the Design and Web Premium bundle.)

The new sprite sheet and CreateJS export features will be useful for developers that want to port old Flash projects to Stage3D, mobile, HTML5, or other platforms, as well as for designers that work with non-Flash developers but want to keep their familiar Flash workflow. This isn’t something that interests me enough to upgrade, personally, but I don’t think it’s a bad idea.

What about you?




View full post on Activetuts+

Apr 19, 2012 Posted on Apr 19, 2012 in Hints and Tips | 10 comments

Creattica Redesign: Fantastic Flash Websites

It’s a month of new beginnings over at our design and inspiration gallery Creattica. April has seen the site undergo a complete redesign with a whole new streamlined grid-style layout for its over 50 different categories. On top of that, Creattica now has better navigation, a new UI Elements section and a growing Freebies area of now over 700 items. All this and over 14,000 featured works from some 100,000 members. It’s quite the site!

But that’s not all, let’s first take a look at some of Creattica’s top Flash website work – and then stay tuned for some exciting news at the conclusion!

1. Interactive agency portfolio

2. Oblique FX

3. THE INCREDIBLE POLO

4. Taua Design

5. Ben Fragau Photography

6. Offices in Greenford

7. iLussori Multimedia

8. Joe Dowdle

9. Karim Balaa – Fresh Contrast

10. Puppetbrain

11. The wishes greenhouse

12. Portfolio: Joonas Paloheimo

13. The Italian Experience 2010 – First Edition

14. Interni Design Studio

15. Flash site for wedding photographer


The Future of Creattica

When we started Creattica (originally Faveup) back in 2007, we wanted it to be one on the top inspiration galleries on the web. And as the site has grown and changed over the years, we find ourselves with what has become one of the biggest, broadest and most in-depth galleries of design out there. So I guess we can say – mission accomplished!

Over these past few months, Envato has really started working on focusing on our core products of Marketplaces and Tuts+ sites. So while we love Creattica, we find ourselves in the regrettable position of having to put the site up for sale soon. We really want it to go to an awesome home, so if anyone would like to express interest in the sale or get more details, please contact us here.

I’m certain we’ll find some new owners who can keep Creattica growing and evolving on into the future. And in the meantime I hope you enjoy the new design and all the gorgeous work as much as I do!



View full post on Activetuts+

Apr 15, 2012 Posted on Apr 15, 2012 in Hints and Tips | 10 comments

Create a Flash “Alphabet Soup” Wordsearch Game – Tuts+ Premium

In this Premium Flash tutorial, you’ll learn how to create a simple wordsearch with a neat “highlighter” interface, which is easy to modify with your own words and layout. It’s a neat diversion you could add to any website, or something you could extend to make into a full game.


Premium Preview

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

In this tutorial we’ll use a series of ActionScript classes to create a classic Alphabet Soup wordsearch game. The objective of the game is to highlight letters to form a word. You will be able to create your own alphabet soup and include your own words.


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+

Apr 12, 2012 Posted on Apr 12, 2012 in Hints and Tips | 10 comments

Accessing the Same Saved Data With Separate Flash and JavaScript Apps

In this tutorial I will show you how to access the same saved data in separate Flash and JavaScript apps, by storing it in HTML5 LocalStorage and using ExternalInterface to reach it with AS3. We will create the same app in both JavaScript and Flash to demonstrate that it is platform agnostic.


Step 1: Examining Local Storage

Local Storage is an exciting part of HTML5 that allows you to do browser side storage that is persistent, meaning it lasts between browser sessions. It only disappears when the user clears their browser cache.

It is a very easy API to use, using simple key-value pairs to store data, and can be used in a few different ways. One way is to use localStorage.setItem('key','value'), and localStorage.getItem('key'). Another way is to use Object Notation: localStorage[key] = value to set a value, and theValue = localStorage[key] to retrieve it. And, if that wasn’t enough, there is yet a third way – Dot Notation: localStorage.key = value to set it, and theValue = localStorage.key to retrieve it.

I am opting for the third way in this tutorial, but if you prefer one of the other ways you can modify the code and it should work just fine. Local Storage does have a few other methods, but these are the only two methods we need: one to set a value and one to retrieve that value.


Step 2: Setting Up the JavaScript Project

We will create the JavaScript app first. You should develop both this and the Flash project on a live server, otherwise you will run into problems. I am using WAMP on my machine as a local hosting environment.

Create a folder to store your project in. Within this folder create two new folders. Name one of them “js” and the other “styles”.

Within the “styles” folder create a new file and name it “style.css”, and within the “js” folder create a new file and name it “externalinterface.js”. Finally, at the root of your project folder create a new file and name it “index.html”.


Step 3: The Index HTML Page

Enter the following code within the “index.html” file you created in the step above.

<!DOCTYPE html>
<html>
<head>
<title>Local Storage with external Interface</title>
<link rel="stylesheet" type="text/css" href="styles/style.css" />
<script type="text/javascript" src="js/externalinterface.js"></script>
</head>
<body>
<div id="wrapper">
<div id="scorewrapper">
<p id="scorediv"></p>

<p id="randomscorediv">Random Score is: </p>

<button type="button" id="scorebtn">Generate Score</button>
</div>

</div>

</body>
</html>

Here we set up the structure of our “index.html” file. We include the “style.css” and the “externalinterface.js” we created in the step above. The scorediv will be updated when we achieve a new high score, and the randomscorediv will be updated each time we generate a new score (click on the button to generate a random score).


Step 4: style.css

Enter the following within the “style.css” you created in the step above.

#wrapper{
	width:400px;
	height:400px;
	margin: 0 auto;

}
#scorewrapper{
	width:400px;
	height:200px;
	background-color:#FFFFFF;
}

#randomscorediv{
	visibility: hidden;
}

body{
	background: #f2f2f2;
	text-align: center;
	padding: 20px;
}

Here we set the app to be centered in the page, set the background-color of the scorewrapper div, and set the randomscorediv to initially be hidden (invisible). When we click on the button we will set the randomscorediv to visible.


Step 5: window.onload

Enter the following code within the “externalinterface.js” you created in the step above.

window.onload = function(){
alert("Window Loaded");
}

Whenever you need to tie into elements on your web page you should make sure the window has loaded first. Since we need to tie into the button, we use the window.onload function provided by JavaScript. Here we are just popping up an alert with the words “Window Loaded”. If you test the page you should see it is working.


Step 6: setScore()

In this step we will code the setScore() function that initially sets the score to 0. Enter the following code within the “externalinterface.js”.

window.onload = function(){
	function setScore(){
		if(!localStorage.score){
			localStorage.score = 0;
		}
	}
}

Here we check whether the localStorage.score exists, and if it doesn’t we initialise its value to 0. When the user first runs the app, or after they clear their cache, this value would not exist – so we need to create it.

Now call this function immediately after you create it, and test by putting it in an alert.

window.onload = function(){
	function setScore(){
		if(!localStorage.score){
			localStorage.score = 0;
		}
	}
	setScore();
	alert(localStorage.score);
}

Step 7: getScore()

We have a way to set our score, now we need a way to retrieve it. That is what the getScore() function will accomplish. Enter the following beneath the setScore() function you created in the step above.

function getScore(){
	if(localStorage.score){
		return(localStorage.score);
	}
}

Here we check that localStorage.score does exist, and if it does we simply return the value it holds. Remove the alert from the previous step, and add the following alert beneath the getScore() function.

function getScore(){
	if(localStorage.score){
		return(localStorage.score);
	}
}
alert(getScore());
}

If you test now you should see the alert again showing the score of “0″.


Step 8: updateScore()

Now that we have a way to set and get our score, we need a way to update it. That is exactly what the updateScore() function achieves. Add the following beneath the getScore() function you created in the step above.

function updateScore(newScore){
	if(localStorage.score){
		localStorage.score = newScore
	}
}

Here we pass as a parameter a newScore; we then set the localStorage.score equal to this value. Remove the alert from the previous step, then add the following beneath the updateScore() function you just created.

function updateScore(newScore){
	if(localStorage.score){
		localStorage.score = newScore;
	}
}
updateScore(10);
alert(getScore());

If you test now, you should see “10″ being alerted, since on line 6 we updated the score to 10.


Step 9: showScore()

Now that we have all our methods in place to manipulate the score, let’s get it showing. Enter the following beneath the updateScore() function you created in the step above.

function showScore(){
    var scoreText = document.getElementById('scorediv');
    scoreText.innerHTML = "Current High Score is "+getScore();
}

Here we get a reference to the scorediv, and alter its innerHTML property to show the current score.

Call this function immediately after you create it.

function showScore(){
    var scoreText = document.getElementById('scorediv');
    scoreText.innerHTML = "Current High Score is "+getScore();
}
showScore();

If you test the page now you should see the words “Current High Score is 10″.


Step 10: Getting a Reference to the Button

We want to run a function when the user click on the button. Add the following beneath the showScore() button you created in the step above.

var scoreBtn = document.getElementById('scorebtn');
scoreBtn.addEventListener('click',getRandomScore,false);

Here we get a reference to the button which we gave the ID scorebtn. We then add an EventListener of type click, which calls the getRandomScore() function that we will create in the next step.


Step 11: getRandomScore()

The getRandomScore() function is where the logic of this application takes place. Add the following beneath the line scoreBtn.addEventListener('click',getRandomScore,false); you entered in the step above.

function getRandomScore(){
	var randScoreText = document.getElementById('randomscorediv');
	randScoreText.style.visibility='visible';
	var randScore = Math.floor(Math.random()* 200000);
	var currentScore = Number(getScore());
	randScoreText.innerHTML = "Random Score is "+randScore;
	if(randScore > currentScore){
		alert("New High Score!!");
		updateScore(randScore);
		showScore();
	}
}

Here, we first get a reference to the randomscorediv and set it to be visible. We then generate a random score by calling Math.floor(Math.random()* 200000), which creates a number between 0 and 200,000. We use our getScore() function to set the variable currentScore (making sure we cast it to a Number), and set the innerHTML of the randScoreText to the randScore.

Lastly we check whether randScore is greater than currentScore, and if it is we show an alert("New High Score!!") and then update the localStorage.score by calling our updateScore() method and passing in the randomScore. We then use showScore() to show the new score.

This concludes the JavaScript application – you can test it here. In the next step we will start devloping the Flash version.


Step 12: Setting Up the Flash Project

In this step we will set up the Flash project.

Create a folder to store your project files in. Now inside this folder create a folder named “js”, and within this folder create a file and name it “externalinterface.js”. At the root of your project folder create a file named “index.html”. Lastly, create a new Flash Project and save it in the root folder, making sure you name it “externalInterface.fla”. Give it a white background, and set the size to 400x200px.


Step 13: Setting Up the Index Page

Add the following to the “index.html” file you created in the step above.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Tuts+ Premium: Demo</title>
<style>
	body {background: #f2f2f2;  text-align: center; padding: 20px}
</style>
<script type="text/javascript" src="js/externalinterface.js"></script>
</head>
<body>
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="400" height="200" id="externalInterface" align="middle">
  <param name="allowScriptAccess" value="sameDomain" />
  <param name="allowFullScreen" value="false" />
  <param name="movie" value="externalInterface.swf" />
  <param name="quality" value="high" />
  <param name="bgcolor" value="#ffffff" />
  <embed src="externalInterface.swf" quality="high" bgcolor="#ffffff" width="400" height="200" name="externalInterface" align="middle" allowScriptAccess="sameDomain" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />
</object>
</body>
</html>

Here we set up our “index.html” file. We include the “externalinterface.js” we created in the step above, and embed the SWF file inside the object tag. If you decided to name your FLA something different, it is important to place the correct value for the SWF where applicable.


Step 14: Setting Up externalinterface.js

Add the following to the “externalinterface.js” you created in the step above.

function setScore(){
    if(!localStorage.score){
		localStorage.score = 0;
	}
}

function getScore(){
	if(localStorage.score){
	 return localStorage.score;

	}
}

function updateScore(newScore){
		localStorage.score = newScore
	}

These are the same functions we used in the JavaScript application, so I will not be explaining them here. It is important to note that I removed the window.onload, however.


Step 15: Setting Up the FLA

In this step we will setup the UI for the FLA you created in the steps above.

Select the Text tool and make sure the following properties are set under the “Character” panel.

  • Color: black
  • Size: 16pt

Now drag a TextField out to the stage and give it the following properties.

  • X: 102.00
  • Y: 14.00
  • W: 210.00
  • H: 25.25

Give it the instance name “currentScore_txt” and make sure the type is set to “Classic Text” and “Dynamic Text” respectively.

Now, drag another TextField onto the stage and give it the following properties.

  • X: 102.00
  • Y: 49.00
  • W: 210.00
  • H: 25.25

Give it the instance name “randomScore_text”.

Go to the Components panel, and drag a button onto the stage. (You can get to the Components panel by going to Window > Components or just by pressing CTRL + F7.)

Give the button the following properties.

  • X: 150.00
  • Y: 110.00
  • W: 100.00
  • H: 22.00

Give it the instance name “scorebtn”.

Within the “Components Parameters” panel, change the label to “Generate Score”.

Select the Rectangle tool and give it a fill color of “#CCCCCC” and no stroke.

Now, drag a rectangle out on the stage. Click to select the rectangle and give it the following properties.

  • X: 118.00
  • Y: 50.00
  • W: 173.00
  • H: 82.00

Now, right-click on the rectangle and choose “Convert To Symbol”; give it the name “alertBox”.

Double click on the rectangle to go into editing mode. Open the Components panel and drag a Button into this MovieClip. Give the Button the following properties.

  • X: 37.00
  • Y: 52.00
  • W: 100.00
  • H: 22.00

Give it the instance name “alertBox_btn”, and change the label to read “OK”.

Drag a TextField into the MovieClip and give it the following properties.

  • X: 29.00
  • Y: 10.00
  • W: 131.00
  • H: 22.00

Type the words “New High Score!!” into the TextField, then close this MovieClip.


Step 16: Main.as

Create a new ActionScript file and save it as “Main.as”. Then, back in your FLA, set Main to be the Document Class.


Step 17: Package and Imports

Add the following within the “Main.as” file you created in the step above.

package  {
	import flash.display.Sprite;
	import flash.events.*;
	import flash.external.ExternalInterface;

	public class Main extends Sprite {

		public function Main() {

		}
	}
}

Here we import the classes we will need, and code our constructor function.


Step 18: ADDED_TO_STAGE

Add the following within Main().

public function Main() {
	addEventListener(Event.ADDED_TO_STAGE,setup);
}

The ADDED_TO_STAGE event runs when the movie has fully loaded. Here it calls a setup function, which we will create next.


Step 19: The setup() Function

Add the following beneath the Main() constructor function.

private function setup(e:Event):void{
	trace("MOVIE READY");
}

If you test now you’ll see that “MOVIE READY” is traced in the output panel.


Step 20: Hiding the Alert Box

You may have noticed the Alert Box we created was showing when the movie first starts; let’s hide it. Enter the following within the setup() function.

private function setup(e:Event):void{
	alertBox.visible = false;
}

Here we set the alertbox to not be visible. Go ahead and test the movie.


Step 21: setScore()

In this step we will use the External Interface class to call our setScore() function that we set up in the JavaScript code. Enter the following beneath the setup() function you created in the steps above.

private function setScore():void {
    ExternalInterface.call("setScore");
}

Here we use the call() method of the ExternalInterface class to run the setScore() function that is in our JavaScript code. The call() method takes as a parameter the name of the JavaScript function to run (as a string). If we had parameters in our setScore() function, we would have included them here too.

We want this function to run when the movie first starts, so add it to the setup() function.

private function setup(e:Event):void{
	alertBox.visible = false;
	setScore();
}

Step 22: getScore()

In this step we will get the score to show in our Flash movie. The JavaScript will be sending the score to Flash, and to do this we will use the External Interface method addCallback() to make the function accessible to it.

Add the following within the setup() function.

private function setup(e:Event):void{
	alertBox.visible = false;
	setScore();
	ExternalInterface.addCallback("getScore", getScore);
}

The addCallback takes two parameters: the name of a function that you want to make accessible via JavaScript (as a string), and an AS3 function that this call will be linked to (as an AS3 function callback). Here we want to make the AS3 getScore() function available to our JavaScript code first; for simplicity’s sake we give it the name getScore() when accessed via JavaScript as well.

We will now code this getScore() AS3 function. Add the following beneath the setScore() function you created in the step above.

private function getScore(score:String):int{
	var theScore:int = int(score);
	return theScore;
}

Here we set up our getScore() function. Since we will be receiving a string back from the JavaScript, we set the parameter as a string, and we return an integer. Inside this function we set up a variable named theScore and cast it to an int; we then return theScore.


Step 23: showScore()

In this step we make the current score display in the Flash movie. Enter the following beneath the getScore() function you created in the step above.

private function showScore():void{
	currentScore_txt.text = "Current High Score is: "+ExternalInterface.call("getScore");
}

Here we set the currentScore_txt.text to display the current score. We use ExternalInterface.call("getScore") to call the getScore function in the JavaScript code, which in turn triggers the getScore() function in our ActionScript code. Remember, this returns the score.

Now add the following within the setup() function.

private function setup(e:Event):void{
	alertBox.visible = false;
	ExternalInterface.addCallback("getScore", getScore);
	setScore();
	showScore();
}

If you test the movie now, you should see the score being shown.


Step 24: addButtonListeners()

We need a way to add some listeners to our buttons, so that when the user clicks on them they do something. Add the following beneath the showScore() method you created in the step above.

private function addButtonListeners():void{
	scorebtn.addEventListener(MouseEvent.CLICK,getRandomScore);
	alertBox.alertBox_btn.addEventListener(MouseEvent.CLICK,hideAlertBox);
}

Add the following highlighted line within the setup() function.

private function setup(e:Event):void{
	alertBox.visible = false;
	setScore();
	ExternalInterface.addCallback("getScore", getScore);
	showScore();
	addButtonListeners();
}

Here we set up our scorebtn to call an AS3 function named getRandomScore(), and we set up the alertBox_btn that is within the alertBox to call an AS3 function named hideAlertBox(). Next we will add these functions.

Add the following beneath the addButtonListeners() function you just created.

private function getRandomScore(e:MouseEvent):void{

}

private function hideAlertBox(e:Event):void{
	alertBox.visible = false;
}

We will finish the getRandomScore() function in the next step. All we do in the hideAlertBox() function is set the alertBox to not be visible. We will be making it visible when the user gets a new high score.


Step 25: getRandomScore()

In this step we will code the getRandomScore() function, where – just like in the JavaScript application we made – all the app’s logic takes place. Add the following within the getRandomScore() body you created in the step above.

private function getRandomScore(e:MouseEvent):void{
	var randScore:int = Math.floor(Math.random()* 200000);
	var currentScore:int = ExternalInterface.call("getScore");
	randomScore_text.text = "Random Score is: "+ randScore.toString();
		if(randScore > currentScore){
		alertBox.visible = true;
		ExternalInterface.call("updateScore",randScore);
		showScore();
	}
}

This works in a very similar way to the JavaScript version. We first generate a number between 0 and 200,000. Then we get the current score by using ExternalInterface.call("getScore"). We set randomScore_text to read out the random score. Lastly we check whether randScore is greater than currentScore, and if it is we show the Alert Box, update the score in Local Storage by using ExternalInterface.call("updateScore",randScore), and call our showScore() method to show the new score.

Check out the demo.


Conclusion

We have used External Interface to access the Local Storage API from HTML5. I hope you have found this tutorial useful and thanks for reading!



View full post on Activetuts+

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+

Page 2 of 157«12345...102030...»Last »
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