简体   繁体   English

如何让图片随机移动并转向页面周围的变化方向? (使用 jQuery 和 css)

[英]How to get a picture randomly move and turn towards the changing direction around a page? (using jQuery & css)

I made a butterfly picture randomly move around a page, simulate a real butterfly.我做了一个蝴蝶图片在页面上随机移动,模拟一只真正的蝴蝶。

$(document).ready(function(){
    animateIMG();
});

function makeNewPosition(){
    // Get viewport dimensions (remove the dimension of the div)
    var h = $(window).height() - 50;
    var w = $(window).width() - 50;
    var nh = Math.floor(Math.random() * h);
    var nw = Math.floor(Math.random() * w);
    return [nh,nw];
}

function animateIMG(){
    var newq = makeNewPosition();
    var oldq = $('img').offset();
    var speed = calcSpeed([oldq.top, oldq.left], newq);
    $('img').animate({ top: newq[0], left: newq[1] }, speed, function(){
      animateIMG();        
    });
};

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;// control the speed here 
    var speed = Math.ceil(greatest/speedModifier);
    return speed;
}

but I don't know how to change direction(rotation angle) to where it move towards.maybe I should calculate the angle between the old and new point.但我不知道如何改变方向(旋转角度)到它移动的方向。也许我应该计算新旧点之间的角度。 then use this plugin to rotate angle?然后用这个插件来旋转角度?

Could anyone help to modify the code?有人可以帮忙修改代码吗?

Thanks!谢谢!在此处输入图片说明

To calculate new angle in degree you can use following function:要以度数计算新角度,您可以使用以下函数:

function getNewAngle(prev, next){
   var x = prev[1] - next[1];
   var y = prev[0] - next[0];
   var ang = Math.atan(Math.abs(y)/Math.abs(x))/(Math.PI/180)
   if(x>0&&y>0)
   return ang;
   else if(x<0&&y>0)
   return ang+90;
   else if(x>0&&y<0)
   return ang-90;
   else
   return ang+180
}

after that you can use之后你可以使用

-webkit-transform: rotate(angle);
-moz-transform: rotate(angle);

for FF and Chrome or JS for all browsers适用于所有浏览器的 FF 和 Chrome 或 JS

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM