Step 5

Let's use our Block class to create objects.

Open the script.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 provisions:

  1. Update the Block.js file by appending the following export statement to the end of it.
    export default Block;
    
  2. The script tag in index.html must include a type attribute as follows. This was already done for you in the starter code.
    <script type="module" src="script.js"></script>
    

In script.js file, remove the following code:

ctx.beginPath();
ctx.rect(20, 40, 50, 50); // x, y, width, height
ctx.fillStyle = "#FF0000";
ctx.fill();
ctx.closePath();

and instead place this statement

const redBlock = new Block(20, 40, 50, 50, "#FF0000");

Notice the use of new keyword to create an instance of the Block class. This must be familiar to you coming from Java/C++.

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

redBlock.draw(ctx);

Save your code again and try it in your browser.