en.javascript.info/5-animation/3-js-animation/move-raf.view/index.html
2015-03-09 19:02:13 +03:00

53 lines
No EOL
1.3 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<!DOCTYPE HTML>
<html>
<head>
<style>
#train {
position: relative;
cursor: pointer;
}
</style>
</head>
<body>
<img id="train" src="https://js.cx/clipart/train.gif">
<script>
train.onclick = function() {
animate(function(timePassed) {
train.style.left = timePassed / 5 + 'px';
}, 2000);
};
// Рисует функция draw
// Продолжительность анимации duration
function animate(draw, duration) {
var start = performance.now();
requestAnimationFrame(function animate(time) {
// определить, сколько прошло времени с начала анимации
var timePassed = time - start;
console.log(time, start)
// возможно небольшое превышение времени, в этом случае зафиксировать конец
if (timePassed > duration) timePassed = duration;
// нарисовать состояние анимации в момент timePassed
draw(timePassed);
// если время анимации не закончилось - запланировать ещё кадр
if (timePassed < duration) {
requestAnimationFrame(animate);
}
});
}
</script>
</body>
</html>