使用JavaScript的GIF图片位置动画

时间:2019-02-21 11:43:19

标签: javascript html animation gif

我正在尝试使用我的代码使用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图片在左上角可见,但没有移动。

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

1 个答案:

答案 0 :(得分:0)

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

this.image = walk.cloneNode(false);

并插入:

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

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

现在为它的 .src 属性分配gif的来源:

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

,然后将CSS position属性设置为绝对

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>