8bitrocket.com
2Jul/120

HTML5 Canvas : Animating Gradients To Create A Retro Atari Style Color Cycle

We just finished our semi-final run into the Atari Pong Developer Contest last week, but I'm still feeling a little "retro".   This weekend I decided to see if I could replicate an old-style Atari color-cycle in HTML5 using the Canvas API alone: no bitmaps or anything other helpers.

The results are below.

(note, if you can't see this try it in Google Chrome)

At first I did not know how I was going to achive this, but the answer came fairly quickly.    I decided to use the Canvas API  createLinearGradient() function.   createLinerGradient() works like this.  You set-up a gradient "line" the represents the direction of the color gradient.  Then you create "color stops" that represent the colors to the gradient.    I'll show this in the code  code later.

To get started, I first, I set-up an animation loop:

function drawScreen() {
}
function gameLoop() {
   window.setTimeout(gameLoop, 20);
   drawScreen() 
}

Next, I created a simple array of objects that represented the colors of the gradient and the color stops.  Colors stops are percentage of the gradient. I started with red, then added yellow, blue, green, purple, and red again.  I had to add red twice so that the color flowed back the beginning.  Notice that the percentages for both reds are only 1/2 of the others (.125 as instead of  .25)

var colorStops = new Array(
 {color:"#FF0000", stopPercent:0},
 {color:"#FFFF00", stopPercent:.125},
 {color:"#00FF00", stopPercent:.375},
 {color:"#0000FF", stopPercent:.625},
 {color:"#FF00FF", stopPercent:.875},
 {color:"#FF0000", stopPercent:1});

Next, inside the drawScreen()  function I created the gradient.

First, I set-up up a gradient on the current path.  The  arguments to the function represent the "line" that the gradient will follow.  Since I wanted the gradient to be in a straight vertical line, I centered it in the middle of the canvas, and drew it directly down to the bottom.

var gradient = context.createLinearGradient( 
               theCanvas.width/2,
               0,
               theCanvas.width/2, 
               theCanvas.height);

Next, I loop through the colorStops array calling gradient.addColorStop() for each color in the array.    A "gradient color stop"() has two arguments: the color and the percentage.  I already set these up in the array, so now they are just applied in a loop.
After each gradient color stop() is added, I increment the percentage of each color by .015.  This effectively moves the color "up" .  If the gradient color stop percentage value goes above 1, I set it back to 0, which moves it back to the bottom of the gradient.

for (var i=0; i < colorStops.length; i++) {     
   var tempColorStop = colorStops[i];     
   var tempColor = tempColorStop.color;     
   var tempStopPercent = tempColorStop.stopPercent;     
   gradient.addColorStop(tempStopPercent,tempColor);    
   tempStopPercent += .015;     
   if (tempStopPercent > 1) {
       tempStopPercent = 0;
   }
   tempColorStop.stopPercent = tempStopPercent;;
   colorStops[i] = tempColorStop;
 }

In reality, the gradient is not being "animated", I'm just changing the location of each color by changing the gradient color Stop percentage.  However, the effect is the same.  It looks like the colors are cycling.

Finally, I display the text using the gradient as the color for fillStyle.

  context.fillStyle = gradient;
  context.fillText ( message, xPosition ,yPosition);

That's it.  I'm sure all kinds of other, way more awesome, effects can be created with animated gradients, but this is just a start.

You can get the code here.

-8bitsteve

14Dec/110

HTML5 Canvas Christmas Tree Drag And Drop Demo And Tutorial

Here is another demo from DevCon5.  Yesterday we showed you an action game, now we will show you something completely different.  A Drag And Drop style decoration application of the type we produced by the dozens ta Mattel throughout the first 10 years of this century.  We present to you: Christmas Tree Decorator.  Music by Mike Peters/The Children Of The Revolution.   This was developed for Google chrome and has not been optimized for other browsers yet.

One of the most interesting thing about this demo (to us) is that we display the mouse button pointer when rolling over things that can be clicked and dragged.  This might not sound like much, but since the HTML5 Canvas does not contain any DOM objects, we had to achieve the effect with our own custom code.  Here is how we did it:

 

  • First, in JavaScript we listen for Canvas “mousemove” event:

[cc lang="javascript"]
theCanvas.addEventListener("mousemove",onMouseMove, false)
[/cc]

 

  • Next we test to see if the mouse if over any of the bulbs.  We keep all bulbs in single array named clickBlocks to make this easy.
[cc lang="javascript"']
function onMouseMove(event) {
		var mouseX;
		var mouseY;

		if ( event.layerX ||  event.layerX == 0) { // Firefox
			mouseX = event.layerX ;
			mouseY = event.layerY;
		} else if (event.offsetX || event.offsetX == 0) { // Opera
			mouseX = event.offsetX;
			mouseY = event.offsetY;
		}
		for (var i =0; i &lt; blocks.length; i++) {

			if (blocks[i].dragging) {
				blocks[i].x = mouseX - BLOCK_WIDTH/2;
				blocks[i].y = mouseY - BLOCK_HEIGHT/2;

			}
		}

		var cursor ="default";
		for (i=0; i< blocks.length; i++) {
			var tp = blocks[i];
			if ( (mouseY >= tp.y) && (mouseY <= tp.y+tp.height) && (mouseX >= tp.x) && (mouseX <= tp.x+tp.width) ) {
				cursor = "pointer";
			}
		}
		theCanvas.setAttribute("style", "cursor:" + cursor);

		for (i=0; i< clickBlocks.length; i++) {
			var tp = clickBlocks[i];
			if ( (mouseY >= tp.y) && (mouseY <= tp.y+tp.height) && (mouseX >= tp.x) && (mouseX <= tp.x+tp.width) ) {
				cursor = "pointer";
			}
		}
		theCanvas.setAttribute("style", "cursor:" + cursor);
	}
[/cc]
  • The key lines in that code, change the cursor depending on what the  mouse is over using CSS

[cc lang="javascript"]

theCanvas.setAttribute("style", "cursor: pointer”);

[/cc]

or

[cc lang="javascript"]

theCanvas.setAttribute("style", "cursor:default" );

[/cc]

Don't forget, you can join our new HTML5 Game Development forums and talk about this kind of stuff all day long!

5Feb/110

Shorter, More Game Focused Tutorials Targeting More Technologies Are Coming

OK, now that our HTML5 Canvas book is in production, we are planning a return to game tutorials that have been so popular here.  However, in 2011, people want more than just AS3 tutorials.  Keeping look back at this space for shorter, more precise code snippets and tutorials on game algorithms and solutions to common problems.   We will present them in AS3, JavaScript/Canvas and/or Corona Lau for mobile.

9Aug/101

HTML5 Canvas Resize On The Fly, In An HTML Page

I've been playing around a lot with the HTML5 Canvas lately, and I discovered some very interesting things that about the size of Canvas as displayed on an HTML page.

The best way to show these is to show a demo of what I'm talking about first.  Here is a link to the demo:
http://www.8bitrocket.com/wp-content/uploads/2010/08/CanvasResizeBlog.html

Note: This demo works best in Google ChromeThe Range controls listed below will not appear in Firefox...yet.

What you will notice on the demo page is a 500x300 Canvas with the text "Text Wrangler" applied to to it.  Below the Canavs are 4 HTML form controls:

  1. A Text box to change the text
  2. An HTML5 Range Control to change the size of the text
  3. An HTML5 Range Control to change the width of the Canvas
  4. An HTML5 Range Control to change the height of the Canvas

Changing the size of the text is a no-brainer.  I added that to show that the Canvas itself could be manipulated with a form control on an HTML page.   However, the range controls for the width and the height of the Canvas are what I'm concentrating on here.  If you play with them you will notice that the width and size of the Canvas can be changed on a page dynamically.  I coded the text to stay in the middle of the Canvas, no matter what the size, with this code:

[cc lang="javascript" width="550"]
var metrics = context.measureText(message)
var textWidth = metrics.width;
var xPosition = (theCanvas.width/2 - textWidth/2);
var yPosition = (theCanvas.height/2);

[/cc]

The measureText() method is native to the Canvas context object.  It only has one property, width.    Since text has a default baseline of "middle", you can center text vertically by placing it at the middle pixel on the screen.  However, text default to a horizontal alignment of "start", which means you need to either set it to "center" or subtract 1/2 the width of the text to get a proper horizontal center at the midpoint of the Canvas.

Now, if you play with the range controls to chnage the width and the height of the Canvas, notice how it interplays with rest of the page.   The form elements move up and down the page as the the height is changed.   The text on the Canvas stays the same scale and centered, no matter how big or small the Canvas might be.   This appears to be the opposite of what is specified in the Canvas API:

The intrinsic dimensions of the canvas interface element equal the size of the coordinate space, with the numbers interpreted in CSS pixels. During rendering, the image must be scaled to fit this layout size.

The image does not appear to scale when the Canvas is resized.  In fact, it simply allows for more of the Canvas to be viewed.  I saw the same effect in Safari.  It is possible that I'm reading the API spec wrong too.  No matter, the cool part is that the Canvas can completely redisplay itself, on the fly, with updated width and height without reloading the page.

It appears to me that the HTML5 Canvas is built to allow for the same types of free-flowing liquid user interfaces that can be created in Flash using "noscale" and JavaScript, but with the added feature of being able to resize the entire Canvas on the fly in real-time.  I've NEVER seen that done with Flash.  I'm not saying you can't do it, I've just never seen it done before.

Here are some code highlights:

The HTML5 form controls below the Canvas interact with the Canvas by listening for events only.  When any control is changed, event handlers are used to capture that change and then render it on the Canvas.

[cc lang="javascript" width="550"]
var context = theCanvas.getContext('2d');
var formElement = document.getElementById("textBox");
formElement.addEventListener('change', textBoxChanged, false);

formElement = document.getElementById("textSize");
formElement.addEventListener('change', textSizeChanged, false);

formElement = document.getElementById("canvasWidth")
formElement.addEventListener('change', canvasWidthChanged, false);

formElement = document.getElementById("canvasHeight")
formElement.addEventListener('change', canvasHeightChanged, false);

[/cc]

Here are the Event Handlers functions.  Notice that to change the width and height of the Canvas, we simply update the the width and height attributes of the Canvas object. (Note: theCanvas is the id of the the Canvas object in the HTML page)

[cc lang="javascript" width="550"]
function textBoxChanged(e) {
var target = e.target;
message = target.value;
drawScreen();
}

function textSizeChanged(e) {
var target = e.target;
fontSize = target.value;
drawScreen();
}

function canvasWidthChanged(e) {
var target = e.target;
theCanvas.width = target.value;
drawScreen();
}

function canvasHeightChanged(e) {
var target = e.target;
theCanvas.height = target.value;
drawScreen();
}

[/cc]

Here is the code in the drawScreen() function that renders the text based on the current width and height of the Canvas.

[cc lang="javascript" width="550"]
var metrics = context.measureText(message)
var textWidth = metrics.width;
var xPosition = (theCanvas.width/2 - textWidth/2);
var yPosition = (theCanvas.height/2);
var tempColor = "#000000";
context.fillStyle = tempColor;
context.fillText ( message, xPosition ,yPosition);
context.strokeStyle = "#FF0000";
context.strokeText ( message, xPosition,yPosition);
[/cc]

Check out the demo again:

http://www.8bitrocket.com/wp-content/uploads/2010/08/CanvasResizeBlog.html

Tagged as: , , 1 Comment
18May/100

HTML 5 Canvas: Using Processing.js To Develop Canvas Apps

This weekend, a friend of mine named Mike Foti noticed my pained expressions when I was talking about the HTML 5 Canvas, and he decided to help salve some of my injuries from my first few tests by pointing me towards a project named processing,js. processing.js is an MIT Media Labs project that began as a way to make the creation of Java Applets easier. It has been ported to work with the HTML 5 Canvas, and so far it looks promising.

The idea behind processing.js is to create a "programming language" that is used to create HTML 5 Canvas apps. If you think of the Canvas as a low-level display API, then processing.js is sort of like what ActionScript is to the SWF specification: it's an easier to use abstraction layer that assists in making applications.

If you look at the processing.js reference, you will see a lot of very useful looking functions that look like they will help take some of the pain put of creating Canvas applications. These include a lot of functions for mouse and keyboard support drawing graphics, etc., but also for application flow like  app loops and frame rates. However, one glaring omission is sound support. My friend had told me that he had seen a lot of Canvas apps that used processing.js on the web, and that makes a lot of sense to me. Since processing.js (or simply, Processing) has been around for a some time for Java, my inkling is that many Java developers have simply ported their Java Processing apps to the Canvas using processing.js. They make for stunning demos, but if they don't explore the Canvas at the API level are they missing something? The lack of sound in many of those demo apps may stem from the lack of support in processing.js, and not the lack of support in the Canvas (although support *is* lacking in the Canavs API). This is just a theory mind-you, but it seems like a fairly obvious situation to me.

Still curious, I sat down today and decided to port my "Gaudy Text Animation" HTML 5 demo from a couple days ago into processing.js. The results were mixed. While processing.js does appear to make some things simpler, it did not solve all my problems.

Here is a run-down of the conversion:

Support Processing.js In An HTML Page

The first thing you need to do when creating an app with processing.js is to include the library in the HTML page. After you have downloaded the current version, and place it somewhere that the HTML code can find. I simply put it in the same directory as my demo file. The following two pieces of code should be put in the section of your page.

[cc lang="javascript" width="550"]

[/cc] Next, you need to add support in JavaScript to get the processing interpreter running. This acts much like the Window load event we create with the native canvas API. [cc lang="javascript" width="550"]
[/cc]

(note: the above code was borrowed and modified from here: http://lethain.com/entry/2008/may/10/getting-started-with-processing-js/ )

In my previous HTML 5 Canvas examples I put all my code in the of the page. However, proper way to create an app with processing.js is to put the majority of the code in the . You do this by creating a
[cc lang="javascript" width="550"]


[/cc]

Application Loop

Now it is time to look at some code that is specific to processing.js. There are two main functions that you need to create for processing.js, both are called automatically.

  • setup(): is used to create the initial application settings
  • draw(): is used to redraw the screen on every frame

In setUp() you set -up things like the dimensions of Canvas, default colors, and the frame rate

[cc lang="javascript" width="550"]
void setup()
{
size(600, 150);
stroke(255);
frameRate(30);
}
[/cc];

In draw() you start making things happen. The most basic this you do, is set the background color (0=black). Also note that variables are declared Java-style, and can be declared outside of the functions. We will be using all of these variables to make the text appear. Notice that many of Phenobarbitals are the same as the ones we used in the "Gaudy Text Animation" HTML 5 demo.


[cc lang="javascript" width="550"]
String text1SizeDir = "up";
String text1Dir = "right";
int text1FontSize = 20;
int text1Xpos = 5;
String text1AlphaDir = "down";
float text1Alpha = 255;
void draw()
{
background(0);
}
[/cc]

Drawing Text Changes

While the setup and execution of a processing.js app differs from a standard Canvas app, the actual code to create the moving text is only slightly modified. This is because processing.js remains and "immediate mode" environment, and thus requires the entire screen to be repainted on every frame. However, in some ways it does feel like it is slightly easier to work with processing.js than the straight Canvas API. This text example might not be a good example of where one might be better than the other.

Drawing the text with processing.js looks like this:

[cc lang="javascript" width="550"]
font = loadFont("_sans");
textFont(font,text1FontSize);
fill(256, 0, 0) ;
text("Hello Canvas",text1Xpos,80);
[/cc]

Drawing the text with the Canvas API looked like this:

[cc lang="javascript" width="550"]
context.font = text1FontSize + 'px _sans';
context.fillStyle = '#FF0000';
context.textBaseline = 'top';
context.fillText ( text1 , text1Xpos, 80);
[/cc]

Note, the fill() function in processing .js is used to change the color of the text and apply an alpha transparency which we will do below.

Moving Text Changes

Moving the text across the screen is very similar in both the Canvas API and processing.js. The major difference comes when you apply the text to the screen (the last line of each example)

Moving the text with processing.js

[cc lang="javascript" width="550"]if (text1Dir == "right") {
text1Xpos += 10;

if (text1Xpos > 460) {
text1Dir = "left";
}
} else {
text1Xpos -= 10;

if (text1Xpos < 10) {
text1Dir = "right";
}

}
text("Hello Canvas",text1Xpos,80);
[/cc]

Moving the text with the Cavas API

[cc lang="javascript" width="550"]metrics = context.measureText(text1)
text1Width = metrics.width;
if (text1Dir == "right") {
text1Xpos += 10;

if (text1Xpos > 600-text1Width) {
text1Dir = "left";
}
} else {
text1Xpos -= 10;

if (text1Xpos < 10) {
text1Dir = "right";
}

}

context.fillText ( text1 , text1Xpos, 180);
[/cc]

Sizing Text Changes

Resizing the text to make it grow and shrink is also very similar in both processing.js and the Canvas API. The major difference is that you set the font and text size with two different calls with processing.js, while you do it with one function call with the Canvas API.

Sizing the text with processing.js

[cc lang="javascript" width="550"]if (text1SizeDir == "up") {
text1FontSize += 1;
if (text1FontSize > 40) {
text1SizeDir = "down"
}

} else {
text1FontSize -= 1;
if (text1FontSize < 20) {
text1SizeDir = "up"
}

}
font = loadFont("_sans");
textFont(font,text1FontSize);
[/cc]

Sizing the text with the Canvas API

[cc lang="javascript" width="550"]if (text1SizeDir == "up") {

text1FontSize += 2;

if (text1FontSize > 40) {
text1SizeDir = "down";
}
} else {

text1FontSize -= 2;

if (text1FontSize < 20) {
text1SizeDir = "up";
}

}
context.font = text1FontSize + 'px _sans';
[/cc]

Text Alpha Changes

Apply the alpha transparency to text is a bit easier with processing.js. Instead of setting a global context as you would with the Canvas API, you can apply the alpha transparency when you set the color of the text for drawing.

Text alpha fade with processing.js

[cc lang="javascript" width="550"]if (text1AlphaDir == 'up') {
text1Alpha +=16;
if (text1Alpha > 255) {
text1Alpha = 255;
text1AlphaDir = "down";
}
} else {
text1Alpha -=16;
if (text1Alpha < 0) {
text1Alpha = 0;
text1AlphaDir = "up";
}

}
fill(256, 0, 0,text1Alpha) ;
[/cc]

Text alpha fade with the Canvas API

[cc lang="javascript" width="550"]if (text1AlphaDir == 'up') {
text1Alpha +=.1;
if (text1Alpha > .9) {
text1AlphaDir = "down";
}
} else {
text1Alpha -=.1;
if (text1Alpha < .1) {
text1AlphaDir = "up";
}

}
context.globalAlpha = text1Alpha;
[/cc]

Text Shadow Changes

I could not find any built-in transformation for making a "shadow" in processing.js (I'm not saying it is not there, I just did not find it...yet), so I simply made two version of the text, one off center by 2 pixels for both x and y, and colored it a lighter color. We simply update both of these every frame instead of setting the global context for shadow as we do with the Canvas API.

Text Shadow with processing.js

[cc lang="javascript" width="550"]fill(200, 200, 200,text1Alpha);
text("Hello Canvas",text1Xpos+2, 82);
[/cc]

Text Shadow with the Canvas API

[cc lang="javascript" width="550"]context.shadowColor = '#DDDDDD';
context.shadowOffsetX = '2';
context.shadowOffsetY = '2';
context.shadowBlur = '2';
[/cc]

Full Code And Examples

See The Example of Gaudy Processing.js Text Demo

See the earlier Example of Gaudy Text Animation" HTML 5 demo using the Canvas API

Full code listing for processing.js Gaudy Text Demo:

[cc lang="javascript" width="550"]



[/cc]

15May/100

HTML 5 Canvas: Creating Gaudy Text Animations…Just Like Flash! (sort of)

Since I have not posted anything about the Canvas in a few weeks I wanted to show some of the experiments I've been working on. Everyone knows that animating text in Flash is very easy and has been around since the technology began. It seems to me, that if the Canvas is going be a "Flash killer", then it must have as robust, if not more-so features than Flash. You can read the Canvas text API here: http://dev.w3.org/html5/2dcontext/#text and see for yourself, but from my view it does not appear to have as many features as Flash at all. Still, I wanted to try it out and see what was possible. Here then is my demo of a HTML5 Canvas text animation.

http://www.8bitrocket.com/wp-content/uploads/2010/07/textblog_movetext.html

Yes, it is true. The HTML 5 Canvas can be used to created some of the same gaudy crap that Flash has been doing for years. Not all of what Flash can do, but some of it. Enough to be dangerous anyway. It's funny, the HTML guys have complained for years about "stupid Flash animations", yet now they have their own tool to do exactly the same thing. Will they practice restraint?

Code Breakdown

Here are the interesting bits of the code. I'm not going to talk about the basics of the canvas, you can get that from here: HTML 5 Canvas For Flash Developers #1: What The #@*! Is The HTML 5 Canvas? or here Exploring The HTML 5 Canvas For Flash Developers #2: Tracking The Mouse To Draw On The Screen.

Animation Loop

It's simple to put text on a Canvas, put animating it is another matter. The Canvas uses an immediate mode drawing paradigm which means he entire screen must be redrawn every time you want to move an object or objects. Unless you are a fan of blitting (we are!) most Flash developers are used to having the player keep track of their objects and redraw them on the screen on each frame. Because of this, they don't need to custom code an animation loop. With the HTML 5 Canvas, you need to create your own loop to have things move on the screen. The code to do this is in the box below. Here are the details of this code:

  • After the page loads (eventWindowLoaded() callback function) we use a setInterval function that should be very familiar to Flash developers (especially those versed in AS2). We set the interval to call appLoop() every 50 milliseconds.
  • The appLoop() only does one thing: calls drawScreen(). This is where you will code all of your "immediate mode" screen manipulations. Remember, there is no display list, so you will be redrawing EVERYTHING on EVERY call to drawScreen().
  • The clearScreen() function is called on every time we are going to redraw. It will perform two functions. It will draw the background, and it will reset and global transformations (i.e. alpha) so that they don't effect the drawing of the background.

[cc lang="javascript" width="550"]function eventWindowLoaded() {

...

setInterval("appLoop()", 50);

...

}

function appLoop() {
drawScreen();
}

function drawScreen() {

clearScreen();
}

function clearScreen() {
context.clearRect(0, 0, 600,400);
context.fillStyle = '#000000';
context.fillRect(0, 0, 600, 400);

}

[/cc]

Moving Text

Now we are going to move some text back and forth across the screen. The steps below describe the code we will create to do this:

  • First, we create a variable named text1Dir that we will use to tell us which direction the text is moving. We want to make sure that we can reverse direction of the text when it reaches the side of the screen.
  • Next we create a variable to hold the calculated x position of the text: text1Xpos;
  • We use a variable named text1 to describe the text that will be displayed: text1 = "Hello Canvas!";
  • In drawScreen() we will start adding code that will redraw the text in text1 every time the function is called.
  • We use the measureText() function of the 2D context to find the width of the text in text1. The function returns an instance of metrics that contain only one property(at this time), width.
  • We use this width to determine if the text has reached the right side of the canvas( (if (text1Xpos > 600-text1Width))) or the left side of the canvas( if (text1Xpos < 10) ).
  • If it has reached either side, we will switch directions using the text1Dir variable ("right" or "left")
  • If we have not reached either side, we will update the position of the text (text1Xpos) based on the direction in text1Dir: "right": (text1Xpos += 10;) or "left": (text1Xpos -= 10;)
  • Finally, we apply the new text to the screen:
    context.fillText ( text1 , text1Xpos, 180);

[cc lang="javascript" width="550"]function eventWindowLoaded() {

...

text1Dir ="right";
text1 = "Hello Canvas!";

...

}
function drawScreen() {

...

metrics = context.measureText(text1)
text1Width = metrics.width;

if (text1Dir == "right") {
text1Xpos += 10;

if (text1Xpos > 600-text1Width) {
text1Dir = "left";
}
} else {
text1Xpos -= 10;

if (text1Xpos < 10) {
text1Dir = "right";
}

}
context.font = '20px _sans';
context.fillStyle = '#FF0000';
context.textBaseline = 'top';
context.fillText ( text1 , text1Xpos, 180);

}

[/cc]

Text Size

We are going to use a similar set of code to that of the movement, for both sizing the text, and for creating the alpha fade on the text. The idea is that we keep track of the direction (for size it will be "up" or "down" instead of "right" and "left" for movement) and reverse accordingly when we reach a limit set in the code.

  • We create a variable to hold the "direction" of the resize: text1SizeDir = "up";
  • We create a variable to hold the font size of the text: text1FontSize=20;
  • In drawScreen() we use text1SizeDir to determine what the next font size for the text will be when we redraw it.
  • We apply the font size to the text like this: context.font = text1FontSize + 'px _sans';, simply appending the font size to the font declaration for context.

[cc lang="javascript" width="550"]function eventWindowLoaded() {

...

text1SizeDir = "up";
text1FontSize=20;

...

}

function drawScreen() {

...

if (text1SizeDir == "up") {

text1FontSize += 2;

if (text1FontSize > 40) {
text1SizeDir = "down";
}
} else {

text1FontSize -= 2;

if (text1FontSize < 20) {
text1SizeDir = "up";
}

}

...

context.font = text1FontSize + 'px _sans';

...

}
[/cc]

Text Alpha Transparency For Fading

Uses an Alpha value for fading the text is very similar to text size and movement except for one major fact: alpha is "global transition" and thus must be used with special care as it will apply to everything on the screen when it is redrawn. For this reason, we will need to add a line of code to the clearScreen() function that resets the alpha before we draw the background. like AS3, alpha is set between the numbers 1 and 0 (AS2 uses a percentage).

  • The text1AlphaDir variable is similar to text1SizeDir as it uses the value "up" and "down", however we will start it with the value "down" which signifies that we will start by fading the text.
  • In drawScreen() we will set context.globalAlpha just before we display the text on the screen. Everything draw after context.globalAlpha will be drawn with the value set for the alpha. It must be reset for anything that does not need the alpha value.
  • We will increment and decrement the alpha value by .1, or 10% each time we redraw the screen.
  • We reset the context.globalAlpha in clearScreen() to 1 so that the background will be drawn with no alpha fade.

[cc lang="javascript" width="550"]function eventWindowLoaded() {

...
text1AlphaDir = "down";
...

}

function drawScreen() {

...

if (text1AlphaDir == 'up') {
text1Alpha +=.1;
if (text1Alpha > .9) {
text1AlphaDir = "down";
}
} else {
text1Alpha -=.1;
if (text1Alpha < .1) {
text1AlphaDir = "up";
}

}
context.globalAlpha = text1Alpha;

...

}

function clearScreen() {

...
context.globalAlpha = 1;
....

}

[/cc]

Text Shadow

Finally, we get to the text shadow. Shadows are fairly easy to create. However, since they are set as part of the global context, you need to be careful how you use them. There are 4 attributes that need to be set to create a shadow:

  • context.shadowColor : The color of the shadow. #XXXXXX hex format is valid.
  • context.shadowOffsetX : The number of pixels to set the shadow on the x axis of the image.
  • context.shadowOffsetY : The number of pixels to set the shadow on the y axis of the image.
  • context.shadowBlur : The number of pixels to spread a blurring effect across both axis

[cc lang="javascript" width="550"] function drawScreen() {

...

context.shadowColor = '#DDDDDD';
context.shadowOffsetX = '2';
context.shadowOffsetY = '2';
context.shadowBlur = '2';

...
}
[/cc]

Full Code Listing

Here is the full code listing for this little gem:

[cc lang="javascript" width="550"]

Your browser does not support the HTML 5 Canvas.

[/cc]

There are more things that you can do with text, but most of them are manipulations of the global context. I'll report back when I have mastered that aspect of the canvas to make something worth showing. However, the point of this tutorial is to show that while some of the FX you can create with the HTML 5 Canvas are similar to those in Flash, creating them takes a lot more low level code than seems reasonable for a Flash designer. Obviously, tools will be created to build some of these things automatically (you can bet Adobe is on it right now), but those tools will still end-up writing out code much like this...all of it clearly visible in the HTML page.

11Apr/100

Exploring The HTML 5 Canvas For Flash Developers #2: Tracking The Mouse To Draw On The Screen

After a week where confusion about the future of the Flash platform has been piled on to developers by moves outside their control, we present the second in our series of HTML 5 Canvas for Flash Developers.  We call these tutorials, but really they are more like explorations.  We are learning this thing at the same time you are learning it.  hopefully these will be beneficial in the long run.

Drawing On The HTML 5 Canvas

One of the most basic things that can be accomplished with an HTML Canvas is drawing with the mouse. In this tutorial we will quickly show you the code for achieving this in HTML 5 with a Canvas element. We are not saying this is the best or most efficient way to do it, just one way to tackle the problem.

Creating A Simple Flash-like"Trace" Window In HTML

The first thing that will drive Flash developers crazy when working in browser JavaScript is the lack of good, out of the box, debugging tools for the web browser. You can install things like Firebug, or use an "alert" box, but we have a found a much simpler, easier way to create a "Flash-like" trace() in JavaScript, on the same page as the Canvas. It is very basic and involves a


[/cc]

 

Test the code.

Flash Developer Digestion

Did you notice something about this code? We never created any objects or MovieClips or Sprites or any other high level object to define the screen, the background, or anything we drew. Drawing the way we did in the is example is akin to using an old "plotter" printer. We kept adjusting the "print head" the moveTo() functions, and then comitted them to "paper" with the lineTo(); and stroke(); This is the method we will use as we continue these tutorials. We will think of the Canvas one a piece of paper that we either continuously draw to (like this example) or needs to be completed erased and redrawn every time time we need to change something (like when you move a sprite in a game).

So you can now see, the HTML 5 Canvas is really just a low-level display area for you to draw on to. In the next lesson we will start adding and tracking bitmap images.

 

 

 

23Feb/100

HTML 5 Canvas For Flash Developers #1: What The #@*! Is The HTML 5 Canvas?

In this set of tutorials, we will explore how the HTML Canvas relates to Flash developers.

So, the first question to answer about the HTML 5 Canvas appears to be this:

"What The #@*! Is The HTML 5 Canvas?"

The short answer is this:

It is an area on a web page set-aside to display and manipulate bit-mapped pixels in "immediate" mode. "Immediate" mode is a way to draw pixels that gives a programmer ultimate control, but requires the screen objects to be tracked and be redrawn entirely in code. You create it with the HTML tag, and you manipulate it with JavaScript. The Canvas is a window into a bitmapped world that, until recently, only existed with plug-ins like Silverlight , Java ,and of course Flash. The Canvas is currently supported (in part) in the latest versions of Firefox, Opera, and Chrome, but not Internet Explorer

The tag was created by Apple initially to support their OSX widgets, and as extension to Safari. The tag was recently adopted as part of the HTML 5 spec after being pushed by both Apple and Google. The HTML 5 spec has many parts besides the , and many of them should seem familiar to Flash developers:

  • H.264 video support (Flash has this already, had it since 2007. Oh, and by the way, Apple's Steve Jobs can go on and on about Flash being proprietary...even though the SWF format is open, but at the same time his love for H.264 makes no sense, as it is CLOSED, proprietary format! )
  • Local storage (more like a Flash shared object, not a Cookie)
  • SVG support: SVG is a vector graphics engine for web browsers. Yep, Flash has had that for a long, long time too.

Since the works in "immediate" mode, it does not have a Display List built-in, like Flash AS2/AS3 (which operate on a "Retained" mode, but can be made to work in "immediate" mode by going right to bitmaps themselves). Instead, you must keep track of all objects and their movement yourself. That means that very simple things that you are used to in Flash, are simply not available in the unless you build support for them yourself. For example, There is no easy way to create tweens, except to create them all in-code. The good news for hardcore programmers, is that sheds a lot of layers and forces you to write clean display code from the get-go. Blitting engines should be par for the course because they will be the an efficient way to display graphics on the Canvas. However, for the legions of designers and designers/programmers who use Flash on a daily basis to create interactive (but not hardcore) web content, the state of the Canvas is a freaking nightmare. While there are a lot of promising tools for JavaScript (i.e. http://processingjs.org/     http://www.ambiera.comcopperlicht/ -thanks Paul) to help c  no tools currently exist that will make the process of creating apps or animations easy for designers. In a few months, when producers at over-zealous agencies have sold their big-name clients on this "Flash replacement that works on the iPad", design and development teams will suffer long and troublesome hours trying to make their claims a reality.

Things For Flash Developers To Note About the HTML 5 Canvas

For Flash developers, a few things stick out as interesting about the .

  • Browser compatibility is an issue. You will have to write code that targets one browser or another. One of first test with Mouse events proved this to me.
  • Recall, that many of us "old" guys (web developers before 2000) used HTML until Flash became viable. We didn't adopt Flash for web sites because Macromedia made it, we adopted it because it worked. The problems with HTML 5 are still the same problems we tried to solve with Flash and HTML 2, HTML 3 and HTML 4: Cross browser issues and the need for real interactivity.
  • Again, There are no real "designer friendly" tools for the Canvas. In fact, a product like the Flash IDE would be perfect to make Canvas apps because it could spit put all the complex JavaScript to make it all work much faster than coding it by hand. I fully expect Flash CS6 will have an "Export as Canvas" option,
  • JavaScript is essentially ActionScript 2.0, so it will be familiar, but also seem like a few steps back from AS3
  • There is still no easy way to "hide" your code, but you can use an JavaScript Obfuscator (thanks to Chris Cutler for this point) that does essentially what a SWF encryptor does for Flash apps.

HTML 5 Canvas Hello World

So, now that you know a bit about the Canvas, here is a "Hello World" app using the element. Be sure to view this with the latest version of Firefox, Chrome, or Safari. In the next lesson we will discuss a bit more about how a program like this works, but for now: Hello World!

The area below is a :

See demo here

Here is the HTML code used to create that Canvas: (by the way, a lot of this code was adapted from the code presented here: http://dev.opera.com/articles/view/html-5-canvas-the-basics/) I've added a "Main()" function because I suspect that is the way my code will be going in the future.

[cc lang="javascript" width="550"]




Your browser does not support the HTML 5 Canvas.



[/cc]

There you have it, a short introduction to the HTML 5 . Next time We'll explore some code in more depth.

 

   
This site is protected by Comment SPAM Wiper.