git @ Cat's Eye Technologies Semicircle-Jam / master src / semicircle-jam.js
master

Tree @master (Download .tar.gz)

semicircle-jam.js @masterraw · history · blame

// SPDX-FileCopyrightText: Chris Pressey, the original author of this work, has dedicated it to the public domain.
// For more information, please refer to <https://unlicense.org/>
// SPDX-License-Identifier: Unlicense


var QUADRANT = Math.PI / 2;
var NUM_SEMICIRCLES = 19;


SemicircleJam = function() {
    this.init = function(cfg) {
        this.canvas = cfg.canvas;
        this.ctx = this.canvas.getContext('2d');
        this.reset();
    };

    this.reset = function() {
        this.ctx.lineWidth = 5;
        this.ctx.strokeStyle = "black";
        this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
        this.columns = 20;
        // this.slots = new Array(this.columns);
        this.xSpacing = this.canvas.width / this.columns;
        this.startPos = Math.floor(Math.random() * this.columns);
        this.pos1 = null;
        this.pos2 = null;
        this.tick = 0;
        this.go();
    };

    this.go = function() {
        var $this = this;
        if (this.interval) {
            clearInterval(this.interval);
        }
        this.interval = setInterval(function() {
            $this.draw();
        }, 200);
    };

    this.closeLoop = function() {
        this.pos1 = this.pos2;
        this.pos2 = this.startPos;
        this.drawSemiCircle();
    };

    this.draw = function() {
        if (this.tick >= NUM_SEMICIRCLES) {
            clearInterval(this.interval);
            return;
        }

        if (this.pos2 == null) {
            this.pos1 = this.startPos;
        } else {
            this.pos1 = this.pos2;
        }
        this.pos2 = Math.floor(Math.random() * this.columns);
        while (this.pos2 === this.pos1) {
            this.pos2 = Math.floor(Math.random() * this.columns);
        }

        this.drawSemiCircle();
    };

    this.drawSemiCircle = function() {
        var x1 = this.pos1 * this.xSpacing + this.xSpacing / 2;
        var x2 = this.pos2 * this.xSpacing + this.xSpacing / 2;
        var x = (x1 + x2) / 2;
        var r = Math.abs(x2 - x);
        var y = this.canvas.height / 2;

        var orientation = this.tick % 2;

        if (orientation === 0) {
            this.ctx.beginPath();
            this.ctx.arc(x, y, r, QUADRANT * 0, QUADRANT * 2, false);
            this.ctx.stroke();
        } else if (orientation === 1) {
            this.ctx.beginPath();
            this.ctx.arc(x, y, r, QUADRANT * 2, QUADRANT * 4, false);
            this.ctx.stroke();
        } else {
            throw new Error("this can't be happening");
        }

        this.tick += 1;
    };
};