gpt4 book ai didi

javascript - 如何在 JavaScript 中旋转跟随光标的图像?

转载 作者:行者123 更新时间:2023-11-27 23:23:56 25 4
gpt4 key购买 nike

我有跟随鼠标光标的图像。

HTML:

<img id="cow" src="https://icons.iconarchive.com/icons/gakuseisean/ivista-2/128/Alarm-Arrow-Right-icon.png" height="30px" width="30px" style="position: absolute; top: 50%; left: 50%;"/> 

Javascript:

var mouseXY = {};
$( document ).on( "mousemove", function( event ) {
mouseXY.X = event.pageX;
mouseXY.Y = event.pageY;
});
var iCow = $("#cow");
var cowInterval = setInterval(function()
{
var cowXY = iCow.position();
var diffX = cowXY.left - mouseXY.X;
var diffY = cowXY.top - mouseXY.Y;
var newX = cowXY.left - diffX / 1000;
var newY = cowXY.top - diffY / 1000;
iCow.css({left: newX, top: newY});
}, 10);

JSFiddle example

如何让图片沿光标方向旋转?
我尝试用 transform: rotate():

来做到这一点
var cowInterval = setInterval(function()
{
var cowXY = iCow.position();
var diffX = cowXY.left - mouseXY.X;
var diffY = cowXY.top - mouseXY.Y;
var newX = cowXY.left - diffX / 1000;
var newY = cowXY.top - diffY / 1000;
var tan = diffX / diffY;
var atan = Math.atan(tan);
iCow.css({left: newX, top: newY, transform: "rotate(" +((-1)*atan - Math.PI/2)+ "rad)"});
}, 10);

但没有成功

最佳答案

在更改光标位置时,您只需要更改 transform(rotate) css 属性,请记住,光标实际上改变了位置。

添加这两个if-else条件,使图片向正确的方向旋转

 if(diffY > 0 && diffX > 0) {

atan += 180;
}
else if(diffY < 0 && diffX > 0) {

atan -= 180;
}

我想这就是你想要的。

var mouseXY = {};
$( document ).on( "mousemove", function( event ) {
mouseXY.X = event.pageX;
mouseXY.Y = event.pageY;
});
var iCow = $("#cow");
var prevXY = {X: null, Y: null};
var cowInterval = setInterval(function()
{


if(prevXY.Y != mouseXY.Y || prevXY.X != mouseXY.X && (prevXY.Y != null || prevXY.X != null)) {

var cowXY = iCow.position();
var diffX = cowXY.left - mouseXY.X;
var diffY = cowXY.top - mouseXY.Y;
var tan = diffY / diffX;

var atan = Math.atan(tan)* 180 / Math.PI;;
if(diffY > 0 && diffX > 0) {

atan += 180;
}
else if(diffY < 0 && diffX > 0) {

atan -= 180;
}

prevXY.X = mouseXY.X;
prevXY.Y = mouseXY.Y;
iCow.css({transform: "rotate(" + atan + "deg)"});
}
}, 10);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id="cow" src="https://icons.iconarchive.com/icons/gakuseisean/ivista-2/128/Alarm-Arrow-Right-icon.png" height="30px" width="30px" style="position: absolute; top: 50%; left: 50%;"/>

关于javascript - 如何在 JavaScript 中旋转跟随光标的图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39572125/

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