当前位置: 代码迷 >> JavaScript >> 使用JavaScript的GIF图像位置动画
  详细解决方案

使用JavaScript的GIF图像位置动画

热度:38   发布时间:2023-06-05 09:34:26.0

我正在尝试使用我的代码使用JavaScript更改图像位置,但是由于某些原因,它不起作用。 有人可以解释原因。

 var walk, isWaveSpawned = true; var walkers = []; function start() { walk = document.getElementById("walk"); draw(); //Animation function } function draw() { if(isWaveSpawned) //Generate a wave of 5 "walkers" { isWaveSpawned = false; for(var i = 0; i < 5; i++ walkers.push(new createWalker()); } for(var o = 0; o < walkers.length; o++) //Add 1px to x position after each frame { walkers[o].x += walkers[o].speed; walkers[o].image.style.left = walkers[o].x; walkers[o].image.style.top = walkers[o].y; } requestAnimationFrame(draw); } function createWalker() { this.x = 0; this.y = 100; this.speed = 1; this.image = walk.cloneNode(false); //Possible cause of issue } 
 <!DOCTYPE html> <html> <body onload="start()"> <img id="walk" src="https://i.imgur.com/ArYIIjU.gif"> </body> </html> 

我的GIF图片在左上角可见,但没有移动。

PS添加了一个HTML / JS代码段,但它输出了一些错误,但最终我看不到这些错误。

首先,让我们修改克隆gif的方式-摆脱这一行:

this.image = walk.cloneNode(false);

并插入此:

this.image = document.createElement("img");

这将创建一个新的空HTML图像元素。

现在,将其.src属性分配为gif的来源:

this.image.src=document.getElementById("walk").src;

并将CSS position属性设置为absolute

this.image.style="position:absolute;";

最后使用以下命令将此新图像元素添加到主体:

document.body.appendChild(this.image);

如果您按下“跑步”,您仍然看不到任何动静,因为还有一些小问题要做!

找到这一行:

walkers[o].image.style.left = walkers[o].x;

并将其更改为:

walkers[o].image.style.left = walkers[o].x + "px";

 var walk, isWaveSpawned = true; var walkers = []; function start() { walk = document.getElementById("walk"); draw(); //Animation function } function draw() { if (isWaveSpawned) //Generate a wave of 5 "walkers" { isWaveSpawned = false; for (var i = 0; i < 5; i++) walkers.push(new createWalker()); } for (var o = 0; o < walkers.length; o++) //Add 1px to x position after each frame { walkers[o].x += walkers[o].speed; walkers[o].image.style.left = walkers[o].x + "px"; walkers[o].image.style.top = walkers[o].y + "px"; } requestAnimationFrame(draw); } function createWalker() { this.x = 0; this.y = 100; this.speed = 1; this.image = document.createElement("img"); this.image.src = document.getElementById("walk").src; this.image.style = "position:absolute;"; document.body.appendChild(this.image); } start(); 
 <body> <img id="walk" src="https://i.imgur.com/ArYIIjU.gif"> </body> 

  相关解决方案