JSFiddle - React, Tailwind, and code Playground

by cdeutsch

HTML

<canvas id="c1" width="400px" height="400px"></canvas>

CSS

#c1 {
    border: 2px dashed black;
}

JavaScript

CanvasRenderingContext2D.prototype.animatedLineTo = function(fromPos, toX, toY, duration, callback) {
    
    ctx.moveTo(fromPos.x, fromPos.y);
    
    // 30 frames per second.
    var ticks = Math.floor((duration / 1000) * 30);

    var incX = (toX - fromPos.x) / ticks;
    var incY = (toY - fromPos.y) / ticks;
        
    //console.log('incX' + incX);
    //console.log('incY' + incY);
    
    var nextX = fromPos.x + incX;
    var nextY = fromPos.y + incY;
    
    var timerId = null;
    
    function draw() {
        //console.log('x' + nextX);
        //console.log('y' + nextY);
        
        ctx.lineTo(nextX, nextY);
        ctx.stroke();
        nextX += incX;
        nextY += incY;
        ticks -= 1;
        
        if (ticks <= 0) {
            clearInterval(timerId);
            if (callback) {
                callback();
            }
        }
    }        
    
    timerId = setInterval(draw, 33.3);
    
    return {
        x: toX,
        y: toY
    };
}

if (typeof(spg)==='undefined') var spg={};

spg.secondsLeft = function(sessionTimeout, sessionStarted) {
    if (sessionTimeout) {
        return parseInt(sessionTimeout) - parseInt((new Date().getTime() - sessionStarted) / 1000);
    }
    else {
        // return a big int.
        return Math.pow(2, 32) - 1;
    }
};

spg.sequence = function() {
    var funcs = [],
        aborted = false,
        finished = false;

    function add(sequenceFunction) {
        funcs.push(sequenceFunction);
    }

    function start() {
        aborted=false;
        next();
    }

    function end() {
        finished=true;
    }

    function next () {
        if (aborted) return;
        if (funcs.length === 0) return end();
        var currFunction=funcs.shift();
        // calls the function with the sequence as an argument
        if (currFunction) currFunction(next);
    }

    function abort () {
        aborted=true;
    }

    return {
        add: add,
        start: start,
        end: end,
 ...