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 f = 1.1;
var s = 1.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) {
s *= f;
if (s > 2.0 || s < 0.5)
{
f = 1.0 / f;
}
animateCanvas();
animateSVG();
animationId = requestAnimationFrame(animateFrame);
}
function stopAnimation() {
if (animationId) {
window.cancelAnimationFrame(animationId);
animationId = null;
}
animate = true;
button.innerHTML = 'Begin Animation';
}
function animateCanvas()
{
ctx.save();
ctx.clearRect(0,0,W,H);
ctx.translate(X, Y);
ctx.scale(s, s);
ctx.fillText(text, 0, 0);
ctx.restore();
}
function animateSVG()
{
svg.scale(s,s);
}
function mod(x, T)
{
if (x > T)
{
x -= T;
}
else if (x < 0)
{
x += T;
}
return x;
}