[英]How to reverse the direction of an animation in HTML5 canvas
我很难理解HTML5动画的工作原理。 我需要一些启示。
我想做的是使矩形动画到画布的底部,然后回到画布的顶部。 看来问题是我没有正确设置矩形的y位置。 我注意到,当我将矩形的速度设置为不同于当前速度时,它会按照我希望的方式做出反应。 矩形想向上移动,但要记住它应该向下移动。 因此,它一直试图决定该怎么做。
最初如何设置矩形的y位置,并且需要不断对其进行更新?
<!doctype html>
<html>
<head>
<title>canvas animation</title>
<style>
#animated {
border: 1px solid black;
}
</style>
</head>
<body>
<h1>canvas animation</h1>
<canvas id="animated" width="500" height="300"></canvas>
<script>
var xLoc = 0;
var yLoc = 0;
var speed = 5;
window.requestAnimFrame = (function(callback) {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
function animateDown() {
var canvas = document.getElementById("animated");
var context = canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
context.beginPath();
context.rect(xLoc, yLoc, 300, 150); // yLoc-canvas.height = -300
context.fillStyle = "rgb(247, 209, 23)";
context.fill();
yLoc += 4;
if (yLoc > canvas.height - 150) {
yLoc -= speed;
} else if (yLoc < 0) {
yLoc += speed;
}
requestAnimFrame(function() {
animateDown();
});
}
window.onload = function() {
animateDown();
};
</script>
</body>
</html>
问题是您没有告诉它反转。 您要告诉它退后,并且陷入一个永无止境的循环中。
更改您的代码,以使其direction
可变(向上/向下):
<script>
var xLoc = 0;
var yLoc = 0;
var speed = 5;
var direction = 1; // Defaults to 'down'
window.requestAnimFrame = (function(callback) {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
function animateDown() {
var canvas = document.getElementById("animated");
var context = canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
context.beginPath();
context.rect(xLoc, yLoc, 300, 150); // yLoc-canvas.height = -300
context.fillStyle = "rgb(247, 209, 23)";
context.fill();
yLoc += speed * direction; // Increase by speed in the given direction
if (yLoc > canvas.height - 150) {
direction = -1; // Move up again (decrease)
} else if (yLoc < 0) {
direction = 1; // Move downwards
}
requestAnimFrame(function() {
animateDown();
});
}
window.onload = function() {
animateDown();
};
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.