Step 4
In Computer Graphics, Animation, and Game Development, there are two kinds of objects: blocks and sprites.
Sprite is a computer graphic which may be moved on-screen and otherwise manipulated as a single entity.
A block on the other hand does not move!
We will create an abstraction for each of these.
- Create a folder
model
in the root of your project. - Create a
Block.js
and aSprite.js
file in themodel
folder.
We will start with the Block.js
file. Add the following code to it:
class Block {
constructor(x, y, width, height, color) {
this.x = x;
this.y = y;
this.height = height;
this.width = width;
this.color = color;
}
draw(ctx) {
ctx.beginPath();
ctx.rect(this.x, this.y, this.width, this.height);
ctx.fillStyle = this.color;
ctx.fill();
ctx.closePath();
}
}
Block
is a class 🎉 Notice the syntax:
- We use the
class
keyword to declare it. - There is a special function called
constructor
which, not surprisingly, is the class constructor! - The attributes of the class are initialized in the constructor using the
this
keyword. Unlike Java/C++, you don't declare fields. The syntax here is similar to Python's class definition. (Python classes are constructed through a special method called__init__()
which uses theself
parameter-instead ofthis
- to reference to the current instance of the class) - Methods are declared with the method declaration syntax (which was explored when we were talking about functions).
- There are no commas between method definitions.