首页 > 解决方案 > 使用 JavaScript 的 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 图像在左上角可见,但没有移动。

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

标签: javascripthtmlanimationgif

解决方案


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

this.image = walk.cloneNode(false);

并插入:

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

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

现在将它的.src属性指定为 gif 的来源:

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

并将 CSS 位置属性设置为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>


推荐阅读