The Search for 60fps
$('.selector').animate({top: '100px'}, 2000);
var element = document.getElementsByClassName('selector')[0];
var current = element.style.top;
var goal = 100;
var step = (goal-current) / 2000;
var tick = function() {
current += step;
element.style.top = current + 'px';
if (current < goal) {
setTimeout(tick, 16);
}
}
tick();
Two major issues!
vSync
Animating Layout Properties
More Reading: http://www.html5rocks.com/en/tutorials/speed/rendering/
More reading: http://csstriggers.com/
60fps means all of this needs to happen in less than ~16ms
only requires compositing, done on the GPU
only requires compositing, done on the GPU
function mousedown(e) {
lastEvent = e;
requestAnimationFrame(tick);
}
function mousemove(e) {
currentX += changeX;
currentY += changeY;
lastEvent = e;
}
function mouseup(e) { lastEvent = null; }
function tick() {
box.style.transform = 'translate('+currentX+'px,
'+currentY+'px)';
if (lastEvent) {
requestAnimationFrame(tick);
}
}
var position = 0;
var velocity = 0;
var acceleration = 1;
var ball = document.getElementById('ball');
function tick() {
velocity += acceleration;
position += velocity;
position = Math.min(position, 180);
if (position >= 180) {
velocity *= -1;
}
ball.style.top = position + 'px';
setTimeout(tick, 16);
}
tick();
Bad!
var position = 0;
var velocity = 0;
var acceleration = 1;
var ball = document.getElementById('ball');
function tick() {
velocity += acceleration;
position += velocity;
position = Math.min(position, 180);
if (position >= 180) {
velocity *= -1;
}
ball.style.transform = 'translateY('+position+'px)';
requestAnimationFrame(tick);
}
tick();
Good!