JSFiddle - React, Tailwind, and code Playground

by siddjain

HTML

<div id="drawing" style="border:1px solid black; width:300px; height:300px"></div>
<button id="animateButton">Begin Animation</button>
<label>FPS: </label>
<span id="fps"></span>

JavaScript

var draw = SVG('drawing');
var text1 = draw.text('Hello').transform({x:100,y:100});
var text2 = draw.text('Hello').transform({x:400,y:100});
var group = draw.group();
group.add(text1);
group.add(text2);
var button = document.getElementById('animateButton');
var animate = true;
var motion = {x:2,y:0};
var animationId = null;
var intervalId = null;
var fps = 0;
var drawWidth = parseInt(draw.parent.style.width);
var drawHeight = parseInt(draw.parent.style.height);
var period = Math.min(Math.abs(drawWidth / motion.x), Math.abs(drawHeight / motion.y));
button.addEventListener('click', animateHandler, false);

function animateFrame(time) {    
    var t = group.transform();
    var x = t.x - motion.x;    
    var y = t.y - motion.y;    
    if (Math.abs(x) > drawWidth || Math.abs(y) > drawHeight)
    {
        // shift in opposite direction
        x += period * motion.x;
        y += period * motion.y;
    }
    group.transform({x:x,y:y});
    fps++;
    animationId = requestAnimationFrame(animateFrame);
}

function animateHandler() {
    if (animate) {
        animate = false;
        button.innerHTML = 'Stop Animation';
        animationId = requestAnimationFrame(animateFrame);
        intervalId = setInterval(updateFps, 1000);
    }
    else {
        animate = true;
        stopAnimation();
    }
}

function updateFps(time) {
    document.getElementById('fps').innerHTML = fps;
    fps = 0;
}

function stopAnimation() {
    if (animationId) {
        window.cancelAnimationFrame(animationId);
        animationId = null;
    }
    if (intervalId) {
        clearInterval(intervalId);
        intervalId = 0;
        fps = 0;
        document.getElementById('fps').innerHTML = fps;
    }

    button.innerHTML = 'Begin Animation';
}