JSFiddle - React, Tailwind, and code Playground

by siddjain

HTML

<div id="container">
    <canvas id="canvas" width="300" height="300"></canvas>
    <div id="drawing"></div>
</div>
<button id="button">Animate</button>

CSS

div#container
{
    width:300px;
    height:300px;
    position:relative;
}

canvas#canvas
{
    border:1px solid black;
    position:absolute;
}

div#drawing
{
    width:300px;
    height:300px;
    position:absolute;
    border:1px solid black;
}

JavaScript

var font = '12px verdana';
var text = 'Hello World!';
var deltaX = 3;
var deltaY = 0;
var X = 10;
var Y = 100;
var W = 300;
var H = 300;
var animate = true;
var animationId = null;
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var draw = SVG('drawing');
var svg = draw.text(text).translate(X,Y).font({family:'verdana',size:12});
var button = document.getElementById('button');
ctx.font = font;
ctx.fillText(text, X, Y);
button.addEventListener('click', clickHandler);

function clickHandler()
{
    if (animate)
    {
        animationId = requestAnimationFrame(animateFrame);
        button.innerHTML = 'Stop Animation';
        animate = false;
    }
    else
    {
        stopAnimation();
    }
}

function animateFrame(time) {    
    X = mod(X + deltaX, W);
    Y = mod(Y + deltaY, H);    
    animateCanvas();
    animateSVG();
    animationId = requestAnimationFrame(animateFrame);
}

function stopAnimation() {
    if (animationId) {
        window.cancelAnimationFrame(animationId);
        animationId = null;
    }
    animate = true;
    button.innerHTML = 'Begin Animation';
}

function animateCanvas()
{
    ctx.clearRect(0,0,W,H);
    ctx.fillText(text, X, Y);    
}

function animateSVG()
{
    svg.translate(X, Y);
}

function mod(x, T)
{
    if (x > T)
    {
        x -= T;
    }
    else if (x < 0)
    {
        x += T;
    }
    return x;
}