2016-06-21 60 views
2

我想用JavaScript使用HTML5画布编写一个足够简单的动画。这是我想要无缝动画的雨滴图像。这是图像:动画图像创建雨效

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

' .y ++',但是你等到它变成'<0';甚至是'this.y <= -199'。你必须等待相当长的一段时间;) – Thomas

回答

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) { 
 
\t position.x += (70 * gameTime.diff/1000); 
 
\t position.y += (110 * gameTime.diff/1000); 
 
\t if (position.x > canvas.width) { 
 
\t \t position.x = 0; 
 
\t } 
 

 
\t if (position.y > canvas.height) { 
 
\t \t position.y = 0; 
 
\t } 
 
} 
 

 
function draw(gameTime) { 
 
\t ctx.clearRect(0, 0, canvas.width, canvas.height); 
 
\t ctx.drawImage(bg, position.x, position.y, canvas.width, canvas.height); 
 
\t ctx.drawImage(bg, position.x - canvas.width, position.y, canvas.width, canvas.height); 
 
\t ctx.drawImage(bg, position.x, position.y - canvas.height, canvas.width, canvas.height); 
 
\t ctx.drawImage(bg, position.x - canvas.width, position.y - canvas.height, canvas.width, canvas.height); 
 
} 
 

 
function loop(tick) { 
 
\t var diff = tick - lastTick; 
 
\t var gameTime = { tick:tick, diff:diff }; 
 
\t update(gameTime); 
 
\t draw(gameTime); 
 
\t requestAnimationFrame(loop); 
 
\t lastTick = tick; 
 
} 
 

 
requestAnimationFrame(loop);
<title>Rain</title> 
 
<meta charset="UTF-8"> 
 
<style> 
 
\t canvas { 
 
\t \t width:100vw; 
 
\t \t height:100vh; 
 
\t } 
 
</style> 
 
<img id="bg" src="https://s31.postimg.org/475z12nyj/raindrops.png" style="display:none;"> 
 
<canvas id="canvas"><h1>Canvas not supported</h1></canvas>

this.y`开始于`0`,并increasing`this
+0

你将如何实现你的代码到我的?你能用它更新小提琴吗? https://jsfiddle.net/qafqyLsy/ 我不知道要粘贴哪些位,哪些不粘贴。 – Zhyohzhy

+0

我所做的所有事情都是更新x的值,以便为您提供一些对角线类型的动作。然后添加一个对requestAnimationFrame的调用,以便渲染函数将循环。更好的办法是在此之外创建你的循环。在你的循环中只需调用update(),draw()和requestAnimationFrame(nameOfYourAnimationLoop)。然后,在你的update()函数中,你可以更新你的Background对象的状态。在draw中,你可以调用Background对象的render()方法(当然,上面没有requestAnimationFrame)。 – ManoDestra

+0

好的,谢谢,我感谢你的帮助。但是关于对角线运动指针,使用我的代码更新对雨的运动仍然没有任何作用,除了以垂直方式坠落之外。你确定你不能更新我的小提琴如何适合你,因为我不认为我做错了吗?抱歉持续。 – Zhyohzhy