The Essential Guide to HTML5

(Greg DeLong) #1

CHAPTER 4


I am using the term objects in both the English and the programming sense. In programming terms, an
object consists of properties and methods, that is, data and coding or behavior. In the annotated links
example described in the first chapter, I demonstrated the write method of the document object. I used
the variable ctx, which is of type 2D context of a canvas object, methods such as fillRect, and
properties such as fillStyle. These were built-in; that is, they were already defined objects in HTML5's
version of JavaScript. For the ballistics applications, I defined my own objects, specifically Ball,
Picture, Myrectangle, and Sling. Each of these different objects includes the definition of a draw
method as well as properties indicating position and dimensions. I did this so I can draw each of a list of
things. The appropriate draw method accesses the properties to determine what and where to draw. I also
included a way to rotate individual objects.


Defining an object is straightforward: I simply define a function called the constructor function for Ball,
Picture, and Myrectangle, and use these functions with the operator new to assign the values to
variables. I can then write code using the familiar dot notation to access or assign the properties and to
invoke methods Ive set up in the constructor function. Here is the constructor function for a Ball object:


function Ball(sx,sy,rad,stylestring) {
this.sx = sx;
this.sy = sy;
this.rad = rad;
this.draw = drawball;
this.moveit = moveball;
this.fillstyle = stylestring;
}


The term this refers to the object thats created when this function is used with the keyword new. The fact
that this.draw and this.moveit are assigned the names of functions is not obvious from looking at the
code, but thats what happens. The definitions of those two functions follow. Notice that they each use the
term this to get at the properties necessary to draw and move the object.


function drawball() {
ctx.fillStyle=this.fillstyle;
ctx.beginPath();


ctx.arc(this.sx,this.sy,this.rad,0,Math.PI*2,true);
ctx.fill();
}


The drawball function draws a filled-in circle, a complete arc, on the canvas. The color of the circle is the
color set when this Ball object was created.


The function moveball doesn't move anything immediately. Looking at the issue abstractly, moveball
changes where the application positions the object. The function changes the values of the sx and sy
properties of the object and when it is displayed next, these new values are used to make the drawing.


function moveball(dx,dy) {
this.sx +=dx;
this.sy +=dy;
}

Free download pdf