gpt4 book ai didi

javascript - 使用 atan2() 向鼠标方向旋转一个 div

转载 作者:可可西里 更新时间:2023-11-01 13:05:44 24 4
gpt4 key购买 nike

我希望鼠标与 div 的 topalign 并且当鼠标随着顶部移动时 div 应该rotate与鼠标对齐的 div。我想使用 atan2。它应该看起来像 this .

Javascript:

$(function() {
var stick = $(".stick"), sHeight = stick.outerHeight(),
sWidth = stick.outerWidth(), atan,
sTop = stick.offset().top, sLeft = stick.offset().left;

$(document).on("mousemove", function(e) {
// console.log(e.pageX, " ", e.pageY)
atan = Math.atan2(e.pageY - sTop , e.pageX - sLeft )
console.log(atan)
stick.css({"transform" : "rotate(" + atan + "rad)"} )
})
})

CSS:

.wrapper{
width: 500px;
height: 400px;
position: relative;
border:1px solid green;
}
.stick{
width: 3px;
height: 200px;
position: absolute;
left: 50%;
top: 50%;
background: green;
transform: rotate(90deg);
}

HTML:

<div class="wrapper">
<div class="stick"></div>
</div>

最佳答案

我做了一些有用的东西 here .

看来您没有正确居中 - 您需要考虑 div 的宽度和容器的中心点

div.$(function(){

var stick = $(".stick"), sHeight = stick.outerHeight(),
sWidth = stick.outerWidth(), atan,
sTop = stick.offset().top, sLeft = stick.offset().left;
$(document).on("mousemove", function(e){
atan = Math.atan2(e.pageY - 200 , e.pageX - 250) + Math.PI/2;
console.log(atan);

stick.css({"transform" : "rotate(" + atan + "rad)"} );


});
});

(我还删除了 css 中的旋转,并将棒放在中心。)

关于javascript - 使用 atan2() 向鼠标方向旋转一个 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33449101/

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