JSFiddle - React, Tailwind, and code Playground
HTML
<html>
<body>
<canvas id="testCanvas" width="400" height="400">Your browser is too old</canvas>
</body>
</html>
JavaScript
//loop helper
if (!window.requestAnimationFrame) {
window.requestAnimationFrame = (function () {
return window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (callback, fps) {
window.setTimeout(callback, 1000 / 60); // frames per second
};
})();
}
//position
var x = 0;
//canvas
var canvas = null;
var ctx = null;
//timing
var time = null;
var frameRate = 33; //33 ~= 30fps, 25 == 40 fps, 16 ~= 60fps
var nextFrameTime = null;
var count = 0;
var framesSkipped = 0;
//render
var shouldRender = false;
//image
var image = new Image();
image.src = "http://aux4.iconpedia.net/uploads/868888537436999746.png";
//loop
function loop() {
//request anim frame
requestAnimationFrame(loop);
//set canvas once able
if (!canvas) {
var temp = document.getElementById("testCanvas");
if (temp) {
canvas = temp;
ctx = canvas.getContext('2d');
}
}
//get time
time = new Date().getTime();
//default next frame time hack
if (!nextFrameTime) {
nextFrameTime = time;
}
//update and render if able
if (canvas) {
//update
while (time >= nextFrameTime) {
//boolean
shouldRender = true;
//increase x
x += 5;
//start from beginning
if (x > canvas.width) {
x = 0;
}
//increment next time
nextFrameTime += frameRate;
//increment count
count++;
}
//render
if (shouldRender) {
//clear
ctx.clearRect(0, 0, canvas.width, canvas.height);
//image
ctx.drawImage(image, x, 200);
//log skipped
framesSkipped += (count - 1);
ctx.font = "normal 36px Verdana";
ctx.fillStyle = "#000000";
...