我创建了三个热气球的 .png 图像。每个都有不同的大小,因此它们散发出“深度”的概念。对这些 .png 进行编码以便它们像热气球一样在我的容器周围移动和漂浮的最佳方法是什么?
我已经尝试了 Spritely 网站上的以下代码,我将其改编为:
$('#balloon1')
.sprite({fps: 3, no_of_frames: 1})
.spRandom({
top: 70,
left: 100,
right: 200,
bottom: 340,
speed: 10000,
pause: 3000
});
我将此代码用于其他两个气球 (#balloon1) 和 (#balloon2),然后将它们各自的 DIV 放入标记为“#sky”的容器 DIV 中
我认为将速度设置为 10000 会使它们漂浮得更慢。
但是,它并没有按照我希望的方式运行。首先,页面加载后,所有三个气球(我最初将它们放置在容器沿线的三个不同位置)立即漂浮到同一个位置,之后它们似乎不会从那个位置移动太多。
有没有一种更简单、更有效的方法让我的三个气球图像在我的容器中随机且逼真地移动?
如能提供帮助,万分感谢!
最佳答案
这是针对您的问题的现有 [部分] 解决方案:
HTML:
<div id="container">
<div class='a'></div>
<div class='b'></div>
<div class='c'></div>
</div>
CSS:
div#container {height:500px;width:500px;}
div.a {
width: 50px;
height:50px;
background-color:red;
position:fixed;
}
div.b {
width: 50px;
height:50px;
background-color:blue;
position:fixed;
}
div.c {
width: 50px;
height:50px;
background-color:green;
position:fixed;
}
JavaScript:
$(document).ready(function() {
animateDiv($('.a'));
animateDiv($('.b'));
animateDiv($('.c'));
});
function makeNewPosition($container) {
// Get viewport dimensions (remove the dimension of the div)
var h = $container.height() - 50;
var w = $container.width() - 50;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh, nw];
}
function animateDiv($target) {
var newq = makeNewPosition($target.parent());
var oldq = $target.offset();
var speed = calcSpeed([oldq.top, oldq.left], newq);
$target.animate({
top: newq[0],
left: newq[1]
}, speed, function() {
animateDiv($target);
});
};
function calcSpeed(prev, next) {
var x = Math.abs(prev[1] - next[1]);
var y = Math.abs(prev[0] - next[0]);
var greatest = x > y ? x : y;
var speedModifier = 0.1;
var speed = Math.ceil(greatest / speedModifier);
return speed;
}
关于javascript - 在页面上随机移动图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13784686/