首页 > 解决方案 > Javascript | 随机移动图像并退出显示

问题描述

我应该为他们在随机方向上做的一些图像制作动画,直到它们直接从屏幕上退出

我发现这个代码片段使我能够从左到右移动单个图像

我怎样才能创建上面写的结果呢?

代码:

<img id="myImage" src="https://i.pinimg.com/originals/4b/ed/d0/4bedd004f9187e0aaa8720b1c29e919a.gif" width="200" height="200"/>
<p>Click the buttons below to start and stop the animation.</p>
<input type="button" value="Play" onclick="moveRight();" />

脚本:

var imgObj ;
var animate ;
function init(){
    imgObj = document.getElementById('myImage');
    imgObj.style.position= 'relative';
    imgObj.style.left = '0px';
}
function moveRight(){
    imgObj.style.left = parseInt(imgObj.style.left) + 5 + 'px'; // move from the left 5 pixels
    animate = setTimeout(moveRight,20); // call moveRight in 20 milliseconds
}
function stop(){
    clearTimeout(animate); // stops the animation
    // add imgObj.style.left = '0px'; if you want to reset the image back to the left side of screen
}
window.onload =init; // starts animation when page loads

标签: javascript

解决方案


从左边开始向右移动。底部/顶部方向每 10-40 步变化一次。步长也是随机的。

var imgObj;
var animate;
var direction;
var counter;
var changeDirectionAfter;

function init() {
    imgObj = document.getElementById('myImage');
    imgObj.style.position= 'relative';
    reset();
}
function reset() {
    imgObj.style.left = '0px';
    imgObj.style.top = '0px';
    direction = Math.random() < 0.5 ? -1 : 1;
    counter = 0;
    changeDirectionAfter = 10;
}
function startAnimation() {
    animate = setInterval(move, 20);
}

function move() {
	var randomRight = Math.floor((Math.random() * 5) + 1);
  var randomTop = Math.floor((Math.random() * 5) + 1);
  if (counter >= changeDirectionAfter) {
  	direction = direction *-1;
    changeDirectionAfter = Math.floor(Math.random() * (40 - 10) ) + 10;
    counter = 0;
  }
	imgObj.style.left = parseInt(imgObj.style.left) + randomRight + 'px';
  imgObj.style.top = parseInt(imgObj.style.top) + (randomTop*direction) + 'px';
  counter++;
}

function stop() {
   clearInterval(animate);
   reset();
}

window.onload =init;
body {
  overflow: hidden;
}
<img id="myImage" src="https://i.pinimg.com/originals/4b/ed/d0/4bedd004f9187e0aaa8720b1c29e919a.gif" width="200" height="200"/>
<p>Click the buttons below to start and stop the animation.</p>
<input type="button" value="Play" onclick="startAnimation();" />
<input type="button" value="Stop" onclick="stop();" />


推荐阅读