我创建了三个.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;
- }