Implementing Dynamic Shape Animation with HTML5 Canvas

Classified in Visual arts

Written on in English with a size of 2.48 KB

Initialization and Global Variables

The following variables manage the state of the shapes and their counts:

var shapes = [];
var tCount = 0;
var mCount = 0;

Setup Function

The init() function starts the animation loop:

function init() {
    draw();
    timer = setInterval(update, 20);
}

Animation Logic

The update() function handles shape generation, movement, and cleanup:

function update() {
    // Generate shapes randomly
    if (tCount < 5 && Math.floor((Math.random() * 200) + 1) == 1) {
        var shape = new Shape();
        shape.x = 400;
        shape.xVel = -5;
        shape.y = Math.floor((Math.random() * 40) + 41);
        shape.width = Math.floor((Math.random() * 20) + 21);
        shape.chooseColor();
        tCount++;
        shapes.push(shape);
    }
    // Additional logic for mCount omitted for brevity...
    for (var i = 0; i < shapes.length; i++) {
        shapes[i].x += shapes[i].xVel;
        if (shapes[i].x <= 0) {
            if (shapes[i].y > 200) tCount--;
            else mCount--;
            shapes.splice(i, 1);
        }
    }
    draw();
}

Rendering Shapes

The draw() function clears the canvas and renders the current shapes:

function draw() {
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    ctx.clearRect(0, 0, c.width, c.height);
    for (var i = 0; i < shapes.length; i++) {
        ctx.beginPath();
        ctx.moveTo(shapes[i].x, shapes[i].y);
        // Logic for drawing triangles based on Y position
        if (shapes[i].y > 200) {
            ctx.lineTo(shapes[i].x + shapes[i].width / 2, 400);
            ctx.lineTo(shapes[i].x - shapes[i].width / 2, 400);
        } else {
            ctx.lineTo(shapes[i].x + shapes[i].width / 2, 0);
            ctx.lineTo(shapes[i].x - shapes[i].width / 2, 0);
        }
        ctx.fillStyle = shapes[i].color;
        ctx.fill();
        ctx.closePath();
    }
}

Shape Object Constructor

The Shape constructor defines properties and color selection:

function Shape() {
    this.x = 0;
    this.y = 0;
    this.xVel = 0;
    this.width = 0;
    this.color = "red";
    this.chooseColor = function() {
        var number = Math.floor(Math.random() * 3);
        this.color = (number === 0) ? "red" : (number === 1) ? "blue" : "yellow";
    };
}

Related entries: