Animation Exercise

Initial Setup

Add the canvas element to your HTML.

<canvas id="canvas"></canvas>

Setup the canvas

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
ctx.canvas.width = 400;
ctx.canvas.height = 100;
ctx.scale(20, 20);

Create the Canvas class

class Canvas {
    constructor(ctx) {
        this.ctx = ctx;

        // Create a new piece when the canvas is initialized
        this.piece = new Piece(this.ctx);
    }
}

Create the Piece class

class Piece {
    constructor(ctx) {
        this.ctx = ctx
        this.x = 1; // start position
        this.y = 1; // start position
        this.color = 'orange';

        // Render the piece on initialisation
        this.render();
    }

    render() {
        this.ctx.fillStyle = this.color;
        this.ctx.fillRect(this.x, this.y, 1, 1);
    }
}

Initialise the canvas and pass in the context

let board = new Canvas(ctx);