我正在尝试使用 HTML5 Canvas 通过 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;
}
}
}
但是我面临两个问题。
- 我根本无法让图像循环播放。它只是掉下来一次,我需要让它循环起来,这样当它开始离开 Canvas 时它会再次继续。
- 一旦我知道如何正确地循环它,就会出现雨不应该完全垂直落下的问题。它需要像图像中的雨滴所示那样沿对 Angular 线落下。
这就是一个足够简单的动画的地方。
这是我的 fiddle ,它包括我的所有代码。非常感谢。
PS:我会寻求任何有关 Javascript 或 CSS 的帮助。但我确实需要仅使用图像的下雨效果!不幸的是,我无法接受其他任何事情。
最佳答案
我建议将循环拆分为动画循环,分别调用 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>
关于javascript - 对图像进行动画处理以创建下雨效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37951649/