Create your first CAKE JavaScript application with this introductory look at the CAKE library.
As we saw in the introductory article, CAKE allows developers to build up a canvas element from a number of individual elements, rather than working with the pixels directly. Now we will look at a sample application that demonstrates this effect.
cake.html
First of all we need a HTML file to host the application. As you can see the HTML is very basic. Apart from the two JavaScript source files (cake.js being the CAKE library source, and cake-demo.js being our own JavaScript file) and a simple style tag to remove the margins, this HTML is the bare minimum needed to display a page.
cake-demo.js
The real work is done in the cake-demo.js script. First a function is created and assigned to the windows onload event. [code]
A Canvas object is created. Although this does create a canvas element in the HTML page, the Canvas object is actually part of the CAKE library. Here we specify the parent element (page.body) and the dimensions (600 x 400). [code]
A Circle is then created. The first parameter is the size of the circle. The second parameter is an object that has been created via literal notation. Literal notation is a feature of JavaScript were the properties of an object can be defined and initialised inline, like {paramapter_a: “a”, parameter_b: 100}. This is a convenient way around JavaScript’s lack of function overloading or optional parameters. Since the properties of this object are labelled they are also self documenting. [code]
A function is added to the Circle to be called every frame. The t parameter is the total time in milliseconds that the application has been running, while the dt parameter is the milliseconds since the last frame. Here we use the total time to modify the scale of the circle along a sine wave. [code]
The Circle is then added as a child of the Canvas. [code]
The whole process is then repeated with a second circle. [code]