Step 9

Let's use our Sprite class to create objects.

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

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

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

- let x = canvas.width / 2;
- let y = canvas.height - 30;
- const dx = 2;
- const dy = -2;
+ const blueSprite = new Sprite(
+   canvas.width / 2,
+   canvas.height - 30,
+   10,
+   10,
+   "#0095DD",
+   2,
+   -2
+ );

Inside the draw function, replace the following statements with a call to draw and move as shown below:

- ctx.beginPath();
- ctx.rect(x, y, 10, 10);
- ctx.fillStyle = "#0095DD";
- ctx.fill();
- ctx.closePath();
- x += dx;
- y += dy;
+ blueSprite.draw(ctx);
+ blueSprite.move();

Save your code and observer the changes in the browser.

The main.js must have the following content at this point:

import Block from "./model/Block.js";
import Sprite from "./model/Sprite.js";
import "./style.css";

const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");

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

const blueSprite = new Sprite(
  canvas.width / 2,
  canvas.height - 30,
  10,
  10,
  "#0095DD",
  2,
  -2
);

function draw() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  redBlock.draw(ctx);

  blueSprite.draw(ctx);
  blueSprite.move();

  window.requestAnimationFrame(draw);
}

draw();