Step 7

Let's use our Block class to create objects.

Open the main.js file and add the following import statement at the very top of the file.

import Block from "./model/Block.js";

For this import statement to work, we need to update the Block.js file by appending the following export statement to its end.

export default Block;

In the main.js file, replace the following statements with the object declaration statement:

- ctx.beginPath();
- ctx.rect(20, 40, 50, 50); // x, y, width, height
- ctx.fillStyle = "#FF0000";
- ctx.fill();
- ctx.closePath();
+ const redBlock = new Block(20, 40, 50, 50, "#FF0000");

Notice the new keyword to create an instance of the Block class. Of course, this syntax must be familiar to you if you come from the Java or C++ universe!

Inside the draw function, after "clearing the canvas", add the following statement:

redBlock.draw(ctx);

Save your code and observer the changes in the browser.