我正在尝试使用HTML5画布使用javascript编写一个足够简单的动画。这是我想要无缝动画的雨滴图像。这是图像:
https://s31.postimg.org/475z12nyj/raindrops.png
这就是我目前制作动画的方式:
function Background() {
this.x = 0, this.y = 0, this.w = bg.width, this.h = bg.height;
this.render = function() {
ctx.drawImage(bg, 0, this.y++);
if (this.y <= -199) { //If image moves out of canvas, reset position to 0
this.y = 0;
}
}
}
我现在面临两个问题。
这是一个足够简单的动画。
这是我的fiddle,它包含了我的所有代码。非常感谢。
PS:我会接受任何有关Javascript或CSS的帮助。但我确实需要降雨效果才能使用图像!不幸的是,我无法接受任何其他事情。
答案 0 :(得分:3)
我建议将循环拆分为动画循环,分别调用update()和draw()。在update()中更新您的状态,然后在draw()中呈现该状态。
像这样的东西(有点粗糙,但你可以做得更好:)):
var lastTick = 0;
var position = { x:0, y:0 };
var bg = document.getElementById('bg');
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
function update(gameTime) {
position.x += (70 * gameTime.diff / 1000);
position.y += (110 * gameTime.diff / 1000);
if (position.x > canvas.width) {
position.x = 0;
}
if (position.y > canvas.height) {
position.y = 0;
}
}
function draw(gameTime) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(bg, position.x, position.y, canvas.width, canvas.height);
ctx.drawImage(bg, position.x - canvas.width, position.y, canvas.width, canvas.height);
ctx.drawImage(bg, position.x, position.y - canvas.height, canvas.width, canvas.height);
ctx.drawImage(bg, position.x - canvas.width, position.y - canvas.height, canvas.width, canvas.height);
}
function loop(tick) {
var diff = tick - lastTick;
var gameTime = { tick:tick, diff:diff };
update(gameTime);
draw(gameTime);
requestAnimationFrame(loop);
lastTick = tick;
}
requestAnimationFrame(loop);
<title>Rain</title>
<meta charset="UTF-8">
<style>
canvas {
width:100vw;
height:100vh;
}
</style>
<img id="bg" src="https://s31.postimg.org/475z12nyj/raindrops.png" style="display:none;">
<canvas id="canvas"><h1>Canvas not supported</h1></canvas>