JSFiddle - React, Tailwind, and code Playground
by jaibuu
HTML
<canvas id="myCanvas" width="600" height="400"></canvas>
<img id="myHexagon" src="http://cdn.sstatic.net/gamedev/img/logo.png?v=123" style="display: none;">
JavaScript
window.requestAnimFrame = (function(callback) {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
var animX = 0;
var frameCounter = 0;
var fps = 0;
var time = new Date();
var counter = 0;
var fpsa = [];
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
context.scale(0.5,0.5);
function animate() {
context.clearRect(0, 0, canvas.width, canvas.height);
animX = Math.sin(++counter/30)*200 + 100 ;
var image = document.getElementById("myHexagon");
for(var i=0; i<1000; i++){
context.drawImage(image, animX+Math.random()*100, 128+Math.random()*100);
}
context.lineWidth=1;
context.fillStyle="#000000";
context.lineStyle="#ffffff";
context.font="18px sans-serif";
context.fillText("fps: " + fps, 20, 20);
++frameCounter;
var currentTime = new Date();
var elapsedTimeMS = currentTime - time;
if (elapsedTimeMS >= 1000)
{
fpsa.push(frameCounter);
var favg = 0;
var avgl = Math.min(5, fpsa.length);
fpsa = fpsa.splice(-avgl, avgl);
for(var i=0;i<fpsa.length;i++){
favg += fpsa[i];
}
favg /= avgl;
fps = favg.toFixed(0);
frameCounter = 0;
time = currentTime;
}
// request new frame
requestAnimFrame(function() {
animate();
});
}
animate();