[英]GIF image position animation using JavaScript
我正在嘗試使用我的代碼使用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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.