Skip to content

Instantly share code, notes, and snippets.

@pjanik
Last active December 14, 2015 23:59
Show Gist options
  • Save pjanik/5169377 to your computer and use it in GitHub Desktop.
Save pjanik/5169377 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<meta charset="utf-8">
<style>
canvas {
border: 1px dashed gray;
}
p {
margin: 0;
}
</style>
<div id="container"></div>
<div>
<p>FPS: <span id="fps"></span></p>
<p>repaint: <span id="repaint"></span> ms</p>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.3.3.min.js"></script>
<script>
(function () {
var requestAnimationFrame = window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame;
window.requestAnimationFrame = requestAnimationFrame;
})();
var maxX = 500,
maxY = 400,
maxSteps = 500,
count = 150,
radius = 15,
steps = 0,
stage = new Kinetic.Stage({
container: 'container',
width: maxX,
height: maxY
}),
layer = new Kinetic.Layer(),
circles = [],
cdata = [],
vx = [],
vy = [],
$fps = $("#fps"),
$repaint = $("#repaint"),
lastTime,
startTime,
circle,
i, len;
circle = new Kinetic.Circle({
x: radius + 2,
y: radius + 2,
radius: radius,
fill: 'red',
stroke: 'black',
strokeWidth: 2
}).toImage({
width: radius * 2.5,
height: radius * 2.5,
callback: function (img) {
for (i = 0; i < count; i++) {
cdata.push({
x: maxX * Math.random(),
y: maxY * Math.random(),
vx: Math.random(),
vy: Math.random()
});
circle = new Kinetic.Image({
image: img,
x: cdata[i].x,
y: cdata[i].y
});
circles.push(circle);
layer.add(circle);
}
// Add the layer to the stage.
stage.add(layer);
function updateTimers() {
var repaintTime = (lastTime - startTime) / steps;
$fps.text((1000 / repaintTime).toFixed(2));
$repaint.text(repaintTime.toFixed(2));
}
function step(timestamp) {
var now = new Date().getTime(),
repaint, i, len, circle, x, y;
lastTime = now;
updateTimers();
for (i = 0, len = count; i < len; i++) {
c = cdata[i];
if (c.x >= maxX || c.x <= 0) c.vx *= -1;
if (c.y >= maxY || c.y <= 0) c.vy *= -1;
c.x += c.vx;
c.y += c.vy;
circles[i].setX(c.x);
circles[i].setY(c.y);
}
layer.draw();
if (steps < maxSteps) {
steps++;
requestAnimationFrame(step);
}
}
// Start animation.
startTime = new Date().getTime();
requestAnimationFrame(step);
}
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment