Step 6
There are two kinds of objects in Computer Graphics, Animation, and Game Development: blocks and sprites.
Sprite is a computer graphic that 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
at 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 the class's current instance.) - Methods are declared using the method declaration syntax. (This syntax was explored in the chapter on JavaScript Functions).
- Inside a class declaration, unlike in object literal, method definitions are not separated by a comma.