JSFiddle - React, Tailwind, and code Playground
HTML
<p>Testing a canvas here:</p>
<canvas id="myCanvas" width="600" height="600">
Your browser does not support the HTML5 canvas tag.
</canvas>
JavaScript
window.requestAnimFrame = (function(callback)
{
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback)
{
window.setTimeout(callback, 1000 / 60);
};
}
)();
function animate(myRectangle, prevTime, nFrames)
{
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
//update times
var date = new Date();
var time = date.getTime();
nFrames = nFrames + 1;
var timeTaken = time - prevTime;
var framesPerMs = nFrames / timeTaken;
//update position
var amplitude = 100;
var period = 2000;
var centerX = canvas.width / 2 - myRectangle.width / 2;
var nextX = amplitude * Math.sin(time * 2 * Math.PI / period) + centerX;
myRectangle.x = nextX;
// clear
context.clearRect(0, 0, canvas.width, canvas.height);
// draw rect
context.beginPath();
context.rect(myRectangle.x, myRectangle.y, myRectangle.width, myRectangle.height);
context.fillStyle = "#8ED6FF";
context.fill();
context.lineWidth = myRectangle.borderWidth;
context.strokeStyle = "black";
context.stroke();
//draw text
context.font = "30pt Calibri";
context.lineWidth = 1;
context.strokeStyle = "blue";
context.strokeText("Frames per second: " + roundNumber(framesPerMs * 1000, 2), 50, 50);
// request new frame
requestAnimFrame(function() {
animate(myRectangle, prevTime, nFrames);
});
}
function start()
{
var myRectangle = {
x: 50,
y: 70,
width: 100,
height: 50,
borderWidth: 5
};
var date = new Date();
var time = date.getTime();
var nFrames = 0;
animate(myRectangle, time, nFrames);
}
function roundNumber(num, dec) {
var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
return...