gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 22:19:12 24 4
gpt4 key购买 nike

我做了一张蝴蝶图片在页面上随机移动,模拟了一只真正的蝴蝶。

$(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;
}

但我不知道如何改变方向(旋转 Angular )到它移动的方向。也许我应该计算旧点和新点之间的 Angular 。然后使用 this plugin旋转 Angular ?

谁能帮忙修改一下代码?

谢谢! enter image description here

最佳答案

要计算新的 Angular ,您可以使用以下函数:

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
}

之后就可以使用了

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

适用于所有浏览器的 FF 和 Chrome 或 JS

关于javascript - 如何让图片随机移动并转向页面周围的变化方向? (使用 jQuery 和 CSS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13375413/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com