WokkaWokka4

Managing animated shapes using an array to store a collection of shape objects.

by Umar

HTML

<canvas id="myCanvas" width="500" height="500">
    <p>Canvas not supported.</p>
</canvas>
        
<input type="button" id="up" value="Up"/>
<input type="button" id="down" value="Down"/>
<input type="button" id="left" value="Left"/>
<input type="button" id="right" value="Right"/>

CSS

* {
    margin: 0; padding: 0;
}
html, body {
    height: 100%; width: 100%; background-color: #000;
}
canvas {
    display: block;
}
#up, #down, #left, #right {
    position: absolute;
    padding: 2px;
}
#up {
    top: 420px;
    left: 30px;
}
#left {
    top: 445px;
    left: 12px;
}
#right {
    top: 445px;
    left: 45px;
}
#down {
    top: 470px;
    left: 25px;
}

JavaScript

$(document).ready(function() {
    var canvas = $("#myCanvas").get(0);
    var context = canvas.getContext("2d");
    var up = 90,
        right = 0,
        down = 270,
        left = 180;

    function WokkaWokka(size, direction, speed, posX, posY) {
        this.startAngle = 0.25;
        this.endAngle = 1.75;
        this.gapClosing = true;

        this.size = size;
        this.direction = direction;
        this.speed = speed;
        this.posX = posX;
        this.posY = posY;
    }

    var WokkaWokkas = new Array();

    WokkaWokkas.push(new WokkaWokka(50, right, 10, 25, 25));
    WokkaWokkas.push(new WokkaWokka(25, up, 5, 250, 25));
    WokkaWokkas.push(new WokkaWokka(75, left, 15, 25, 250));

    function renderGrid(gridPixelSize, color) {
        context.save();
        context.lineWidth = 0.5;
        context.strokeStyle = color;

        // horizontal grid lines
        for (var i = 0; i <= canvas.height; i = i + gridPixelSize) {
            context.beginPath();
            context.moveTo(0, i);
            context.lineTo(canvas.width, i);
            context.closePath();
            context.stroke();
        }

        // vertical grid lines
        for (var j = 0; j <= canvas.width; j = j + gridPixelSize) {
            context.beginPath();
            context.moveTo(j, 0);
            context.lineTo(j, canvas.height);
            context.closePath();
            context.stroke();
        }

        context.restore();
    }

    function setAngles(WWM) {
        if (WWM.startAngle <= 0) WWM.gapClosing = true;
        else if (WWM.startAngle > 0.25) WWM.gapClosing = false;

        if (WWM.gapClosing) {
            WWM.startAngle = WWM.startAngle + 0.05;
            WWM.endAngle = WWM.endAngle - 0.05;
        }
        else {
            WWM.startAngle = WWM.startAngle - 0.05;
            WWM.endAngle = WWM.endAngle + 0.05;
        }
    }

    function renderContent(WWM) {
        context.save();
        context.beginPath();
       ...