Monday, August 29, 2011

First Look at Javascript animation

Javascript and AS3 are based off of similar coding principles in that they are based on ECMAscript 5. But trying to do a simple animation in Javascript is alot different.for instance If I wanted to move a block across the screen in flash I would follow these steps.
1. take the blocks x corrdinate and call and onEnterEvent add 1 to the value blocks x position.

this would look something like this (if I was writting a timeline script).

addEventListener(Event.ENTER_FRAME, doMove);
doMove(event:Event){
block.x += 1;
}

In javascript it is a little different this is because the position of an element in the DOM is apart of the elements style property. First you have to make sure that the element is positioned absolutely. So what I did was make a div called box.
than in the css file I gave the box some style

#box{
width:50px;
height:50px;
background-color:#003366;
position:absolute;
left:1px; <--- this is important
}

Now the interesting thing to note is that even though you could physically see the box on the screen. if you did not explicitly set the left attribute, you could not access it. This must have something to do with the browsers ability to read and write CSS rules( not sure).
For instance in AS3 you can access an objects x field with out having to first initialize it because it is a member of the object when it is made. That being said:
//I make a box object called box1 it is global only for this example
var box1 = null;
// I then give a default value for the left position
box1.style.left = '1px';
//than I make a function that will update the left value every iteration of a loop
function doMove()
{
box1.style.left = parseInt(box1.style.left)+1+'px';
setTimeOut(doMove,20);
}
//start the function when the you click the screen
window.onmousedown= doMove;

Here is a link to the box moving in javascript.

No comments:

Post a Comment