javascript - 使用 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 片段,但它输出了一些错误,而最终我看不到这些错误。
解决方案
首先让我们修改克隆 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>
推荐阅读
- google-api - Google Classroom api - 补丁草稿等级
- php - 如何卸载php 7.1
- excel - 如何创建从封闭表中跳过 VBA 中的单元格的循环
- r - 如何通过重叠特征分割多边形?
- python - 如何根据过去的 X 数据量不断计算某些东西?(详情请查看信息)
- swift - 具有多个闭包参数的函数给出错误“表达式解析为未使用的函数”
- python - 测试字符串中“x”或“y”的正确方法?
- r - 库中的错误(dplyr):没有名为“dplyr”的包
- javascript - HTML - 从另一个站点提取文本
- spring - Spring JPA:主键是外键 - 此类未定义 IdClass