javascript - 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
解决方案
从左边开始向右移动。底部/顶部方向每 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();" />
推荐阅读
- django - 如何在 Django 中的类别下显示子类别?
- google-cloud-platform - 部署后云函数 URL 不起作用
- javascript - 如何在滚动时使用 JavaScript 检测特定的 CSS 类?
- python-3.x - 在 Keras 中加载数据集时如何修复错误?
- flutter - 如何使用密码验证 (dd-mm) 格式的当前日期
- javascript - 如何在 Aurelia 中对表单验证进行单元测试
- android - EditText 没有在自定义复合视图中获得焦点
- php -
DOMDocument saveHTML() 中的标记后出现换行符 - coreml - 如何创建可更新的 coreml 模型?
- javascript - 如何在 Reactjs 中映射和过滤