Saturday, October 23, 2010

Front Trends 2010 in a few words - 2nd day

First day of FT2010 was described [here]. Now let me share my experiences from the second one.


First speech of the second day of Front Trends was opened by Jake Archibald. It was all about designing and creating flexible APIs. We learned that API needs to be designed before any code is written - otherwise young boys will watch movies about cocks with their mothers. Also - good API is like Patrick Stewart (who hates PHP) and most of the world's problems are caused by Java. Jake discussed also different use cases of typical API on the example of creating the carousel element on the web page. It was one of the most interesting presentations during the FT - both in terms of content and form. Great job! [watch it here]

Another lecture was prepared by Christian Johansen. He presented the idea of Test Driven Development using Live Search jQuery plugin as an example. There was a bit of theory and a lot of live coding.

I was really looking forward for the PhoneGap speech by Kamil Trebunia, former employee of Nokia. He started with advantages of cross-device development and presented basic aspects of creating applications using HTML5 techniques. Then showed crossmobile tools like Phonegap or Titanium Mobile with their pros & cons. After discussing jQuery Mobile and Sencha Touch as examples of JS mobile frameworks Kamil shows few hacks and tricks for performance boost, like optimizing reflows (using CSS3 transformations instead of changing absolute style attributes like positions or margins, etc.). After the speech we had nice talk about future of cross mobile development together with Markus Leutwyler and one Wikipedia guy from Italy, unfortunately I forgot his name.

Another very interesting speech was prepared by Professor of Mechanical Engineering from Dortmund University of Applied Sciences and Arts, Stefan Gössner. He began his speech with the question - why not to use modified physics engines for games, like Box2d, in scientific simulations? And, in addition, why not to make it as a web application using Javascript & Canvas? Results of his work was amazing - prof. Stefan presented couple of real life examples of mechanical simulations, like solid body on a spring, typewriter or Mercedes Benz's wipers mechanism. Everything works smooth, fast and most importantly - it looked convincingly. Rest of the talk he was describing different representations of physics data like vectors, matrices etc., everything supported with performance tests.

Peter-Paul Koch, author of the well known Quirksmode.org was the last speaker at Front Trends. He was generally talking about the future of the mobile apps - about 10$ smartphones available worldwide in 2018, about ridiculous at least 41 App Stores, free HTML5 apps with paid content, shared via Bluetooth on wide variety of devices and systems. Ppk mentioned also some hypothetical javascript mobile browser's events, like onphonecall or oncompasspointnorth and gives examples of using them in real life applications. He also answered lot of questions about his vision of the mobile future and some less clever also ( - You think iPad is more mobile or desktop device? - Yes.).

Unfortunately I was not able to be present on all of the lectures - I regret the most "Mobile UX and current trends in mobile design" by Anthony Ribot. If there is any video from that one please publish it somewhere!

I would like to thank anyone I was talking with. Also organizers for that awesome event. And guys from PALM for my PRE phone (I hope so, it still stuck at customs:) ). It was exciting to meet first league of world's frontend developers not even leaving my own city. I hope I will feel the same after FalsyValues!

Thursday, October 21, 2010

Front Trends 2010 in a few words

First day of Front Trends conference is behind us now. First time ever so many JavaSript 'gurus' met in Poland. As the participant of this event I would like to write a few words about it.

Conference was opened by the organizers - Damian Wielgosik & Pawel Czerski. They said few words about the dreams, writing anonymous emails to famous people, and organizing conference from scratch. I respect Damian for everything he is making for Javascript community, but that part looks really bad. It was delayed, unprepared, and above all just uninteresting for the developers. Searching for #ft2010 on twitter just after it starts I could read a lot of comment like that.
But the worst part of the opening was short speech made by ZlapTaxi guy, who said at the beggining that if you want to make cross-mobile application you have to build huge team of Java, Objective-C, Symbian C, Cpp and God only knows what other developers (have you ever heard of PhoneGap? Oh, sorry, it was next presentation and it is so hard to read all that up to date stuff in the Internet). After explaining how to use his catch-a-taxi app and announcing a contest, he state that if you will find girl in Front Trends tshirt somewhere there, she could helps you order a taxi. So why he build that app for if there are girls to do this? Never mind.

First speech I was attending in was "You know webOS" by Markus Leutwyler. Markus presented webOs history, main tasks, and devices that webOS is running on (even kind of printer with that Os - sick!). After that he discussed basics of webOs development - Mojo framework, building and connecting Scenes & Controllers. He finished with few words about jailbreaking and rooting Palm devices, testing & packaging created apps. Everything was clear and nice (especially I like his pronunciation of the name "webOS", maybe it is Swiss accent or something, I'm not sure:) ), but if you ever create even one simple webOs application - you already know everything Markus was talking about. For sure - if I hadn't written anything on webOS before,I would start after this lecture!

In the second talk Robert Nyman showed us main features of HTML5. He said a little about history of language, coercion, falsy values, video and audio elements and it's hacks, few words about webstorage and cookies and gives us nice example of FileAPI. Each comparison of 'old' methods and 'brand new HTML5' manner was served in funny, enjoyable way, with a lot of Forrest Gump or other pop culture references (Why Rachel from "the Friends" sitcom was sad after her boyfriend left her? Because she needs closure!)

Andrea Giammarchi a.k.a. WebReflection prepared nice speech about Javascript performance on different devices. He showed us couple of performance tests and explained each one. As the summary of the talk he state that if you want you app to run fastest as possible you have to create it for given browser and use browser-specific hacks for performance boost. Check Andrea's blog for more details.

Before the lecture of Kyle Simpson I was wondering, what is that all Javascript Middle-end stuff about. He explained everything using nice, simple slides and charts in about a half of his time. Starting from traditional MVC architecture (the "boring" one) he presents new Clients Views Controllers architecture in which all the logic made in the templates before, is now moved to the middle-end layer. In this manner of creating web applications there are no single condition or equation in the templates. Sounds great. Next he showed sources of his Shortie.me page build using his Bikechain.js - minimal server-side JavaScript wrapper environment.

Last speech for today was prepared by Douglas Crockford. I must say that I was a little bit disappointed - I've already seen this! His "Javascript server-side" lecture was modified version of his Loopage presentation from YUI Theater. Yes, I know - that is all my false - I watch every Crockford's video available on the Internet.
Undeniably - the best part of today's event was Panel Discussion with Tantek Celik, Peter-Paul Koch & Mr Crockford. It was more than one and a half hour of pure Javascript discussion, so it is impossible to quote everything. Most interested things I've learned from the panel:
- differences between API's and implementations are consequence of using technology before specification is finished,
- Flash took place in the web market because HTML was not able to make awesome things. Now it is, so we have to forget about Flash,
- web developers are the most stupid and the laziest people ever
- people are watching so much porn that they have to download JS libraries each time they visit site that is using it:)
- and if you want to be good JS developer you must use js frameworks and you couldn't use it simultaneously.

Tomorrow second day. I'm really looking forward for it!

UPDATE: read next part [here]

Friday, October 15, 2010

Four methods of Javascript animation

Quoting Wikipedia:
Animation is the rapid display of a sequence of images in order to create an illusion of movement.

There are few methods to achieve that effect in JS, and I will discuss four of them in here.

1. Canvas animation
I used canvas animation in my Javascript game tutorial, but let's describe it once again. As an example, I will animate jump frames from my very favorite game days ago, Prince of Persia, you can find it on the right side of the post.
Before stating any animation related stuff it's necessarily to define few variables common for all four methods. Let's do this:
var width = 100,
    height = 86,
    frames = 10, 
//our PoP jumping animation has 11 frames, but we count from 0
    
    actualFrame = 0,
       
    posX = 100,
    posY = 100,
//X & Y position of the element

    canvas = document.createElement('canvas'),
//'canvas' variable will be always main element of an animation, not always  type
    canvasStyle = canvas.style,
    ctx = canvas.getContext("2d"),
    image = document.createElement('img');
 
    image.src = 'sprite.jpg';
 
    canvasStyle.position = "absolute";
    canvasStyle.top = posX;
    canvasStyle.left = posY;

    canvas.width = width;
    canvas.height = height;
//width & height are assigned directly to th canvas, not to the canvasStyle because in the other case it would scale the element, not change its size.
    document.body.appendChild(canvas);
 
var draw = function(){
//main function for rendering each frame, here will all the animation logic goes.
} 

setInterval(draw, 80);
//main loop        
To animate our character we need just to display next frames of the jump on the canvas. It's not necessarily to clear whole surface each time in this particular case, because it has the same size as single frame. The draw function will looks like that:
var draw = function(){
    ctx.drawImage(image, 0, height * actualFrame, width, height, 0, 0, width, height);
//the attributes are: image to draw, X coord of the source image, Y coord of the source image, width & height of the cut piece (frame size), X & Y destination coords (our canvas) and destination frame size (not always the same as the source one, eg in case of scaling the frame)

    if (actualFrame == frames) {
        actualFrame = 0;
    } else {
        actualFrame++;
    }
//looping the frames, it is also the common part of all draw() function in this post
} 
So that is the first method of JavaScript animation.
Pros:
- it uses canvas (the future of HTML5 games)
- it's possible to scale, rotate, flip, etc. the frames in browsers that support canvas but no CSS3
- probably much more

Cons:
- need to clear whole canvas to draw another frame
- not supported in old browsers
- quite complex math for display single frame

Life example: [1. Canvas Animation]

2. Background looping
I think it was one of the firstmethods of sprite's animation in web browsers. It is the simplest way ever. Just create div element with background, and change backgroundPosition on each frame. Piece of cake. Try:
var canvas = document.createElement('div'),
//div element is now our 'canvas'
    canvasStyle = canvas.style;
    
    canvasStyle.backgroundImage = "url(sprite.jpg)";
//and our image is just it's background
    canvasStyle.position = "absolute";
    canvasStyle.top = posX;
    canvasStyle.left = posY;

    canvasStyle.width = width;
    canvasStyle.height = height;
//width & height are now assigned to the 'style', not directly to the element
    document.body.appendChild(canvas);
    
var draw = function(){
    canvasStyle.backgroundPosition = "0 -"+height * actualFrame;
//each frame background image moves up, that's why there is minus sign before the value, you can multiply (height * actualFrame) by negative one, it gives the same effect
(...) //here goes frame changing logic from the 1st example
}
Pros:
- simplicity
- works everywhere

Cons:
- not possible to scale, rotate, etc. without CSS3

Example: [2. Background looping animation]

3. Clip-rect method
Hmm, but what when we wan't our game to run on full screen, or on different devices with various resolutions? Changing size of the div from second example gives nothing, just looks ugly. So this is where I introduce clip:rec(), Css attribute of img element. Quoting W3schools:

The clip property lets you specify the dimensions of an absolutely positioned element that should be visible, and the element is clipped into this shape.

Let's try:
var canvas = document.createElement('img'),
//image is not the canvas
    canvasStyle = canvas.style;
    
    canvas.src = 'sprite.jpg';
(...)//rest of the attributes
var draw = function(){
    var frameTop = height * actualFrame, 
        frameLeft = 0, 
        frameRight = width, 
        frameBottom = frameTop + height;
//a little math here for each frame
                                 
    canvasStyle.clip = "rect("
        +frameTop +"px " //top
        +frameRight +"px " //right
        +frameBottom +"px " //bottom
        +frameLeft +"px )"; //left
                                      
    canvasStyle.top = posY - height * actualFrame;
//IMPORTANT: even if we crop piece of source image, it's top & left attrs dont change - it's necessarily to move it to the fixed position. That's what I made above.
Pros:
- only one element needed (just img)
- possibility of scaling without CSS3
- crossbrowser

Cons:
- not possible to rotate, flip, etc
- very lot of math needed on each move/frame changing.

Example: [3. Clip-rect method]

4. Div with overflow:hidden
The last way of animation I want to present is simplest than 3rd one, better than 2nd, and doesn't use canvas. The whole philosophy is to create one div element with image inside, display only part visible in div, and move the image in proper way. Like this:
var canvas = document.createElement('div'),
    canvasStyle = canvas.style,
    image = document.createElement('img'),
    imageStyle = image.style;
    
    image.src = 'sprite.jpg';
//div is the 'canvas' now, but it has an image inside
    
    canvasStyle.position = imageStyle.position = "absolute";
    canvasStyle.top = posX;
    canvasStyle.left = posY;
    canvasStyle.overflow = "hidden";
//that is very important
    canvasStyle.width = width;
    canvasStyle.height = height;
    
    imageStyle.top = 0;
    imageStyle.left = 0;
    canvas.appendChild(image);
    document.body.appendChild(canvas);
//put image in the canvas/div and add it all to the body of the document.    
var draw = function(){
                                 
    imageStyle.top = -1*height * actualFrame;
//as in the 3rd example - direction of the move must be negative. Otherwise animation will be played backwards   
    if (actualFrame == frames) {
        actualFrame = 0;
    }
    else {
        actualFrame++;
    }
    
} 
Pros:
- possibility of scaling without CSS3
- crossbrowser
- much simpler than clip:rect()

Cons:
- not possible to rotate, flip, etc
- two elements needed (img & div)

Example: [4. Div with overflow:hidden]

Changing size of animated elements is very important in gamedev. So as simplicity. That's why in my new JS game engine I will implement both, canvas and overflow:hidden methods. You can find all the sources on my GitHub account: [Javascript animation]