javascript – 在页面上随机移动图像

前端之家收集整理的这篇文章主要介绍了javascript – 在页面上随机移动图像前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我创建了三个.png热气球图像.每个都是不同的大小,以便他们给出“深度”的想法.编码这些.png的最佳方法是什么,以便它们像热气球一样移动并漂浮在我的容器周围?

我已经尝试了Spritely网站上的以下代码,我将其改编为:

  1. $('#balloon1')
  2. .sprite({fps: 3,no_of_frames: 1})
  3. .spRandom({
  4. top: 70,left: 100,right: 200,bottom: 340,speed: 10000,pause: 3000
  5. });

我把这个代码放到另外两个气球(#balloon1)和(#balloon2)然后我把他们各自的DIV放到一个标有“#sky”的容器DIV中

我认为将速度设置为10000将使它们漂浮得更慢.

然而,它并没有像我希望的那样发挥作用.首先,一旦页面加载,所有三个气球(我最初位于容器的三个不同位置)立即漂浮到同一个位置,之后它们似乎没有从那个位置移动太多.

是否有一种更简单,更有效的方法让我的三个气球图像随机和逼真地在我的容器周围移动?

非常感谢你,如果你能提供一些帮助!

解决方法

以下是您问题的现有[部分]解决方案:

HTML:

  1. <div id="container">
  2. <div class='a'></div>
  3. <div class='b'></div>
  4. <div class='c'></div>
  5. </div>

CSS:

  1. div#container {height:500px;width:500px;}
  2.  
  3. div.a {
  4. width: 50px;
  5. height:50px;
  6. background-color:red;
  7. position:fixed;
  8.  
  9. }
  10. div.b {
  11. width: 50px;
  12. height:50px;
  13. background-color:blue;
  14. position:fixed;
  15.  
  16. }
  17. div.c {
  18. width: 50px;
  19. height:50px;
  20. background-color:green;
  21. position:fixed;
  22.  
  23. }

JavaScript的:

  1. $(document).ready(function() {
  2. animateDiv($('.a'));
  3. animateDiv($('.b'));
  4. animateDiv($('.c'));
  5.  
  6. });
  7.  
  8. function makeNewPosition($container) {
  9.  
  10. // Get viewport dimensions (remove the dimension of the div)
  11. var h = $container.height() - 50;
  12. var w = $container.width() - 50;
  13.  
  14. var nh = Math.floor(Math.random() * h);
  15. var nw = Math.floor(Math.random() * w);
  16.  
  17. return [nh,nw];
  18.  
  19. }
  20.  
  21. function animateDiv($target) {
  22. var newq = makeNewPosition($target.parent());
  23. var oldq = $target.offset();
  24. var speed = calcSpeed([oldq.top,oldq.left],newq);
  25.  
  26. $target.animate({
  27. top: newq[0],left: newq[1]
  28. },speed,function() {
  29. animateDiv($target);
  30. });
  31.  
  32. };
  33.  
  34. function calcSpeed(prev,next) {
  35.  
  36. var x = Math.abs(prev[1] - next[1]);
  37. var y = Math.abs(prev[0] - next[0]);
  38.  
  39. var greatest = x > y ? x : y;
  40.  
  41. var speedModifier = 0.1;
  42.  
  43. var speed = Math.ceil(greatest / speedModifier);
  44.  
  45. return speed;
  46.  
  47. }​

Live JSFiddle Demo

猜你在找的JavaScript相关文章