【发布时间】:2021-08-31 11:55:29
【问题描述】:
我正在尝试使用 HTML 页面上的 mousemove 事件来旋转 DIV 元素。我想使用点积找到一个旋转角度。我知道也可以使用 Math.atan2,但我想在我的示例中使用点积。
到目前为止,我尝试实现以下公式:
cos(角度) = 点(a, b) / (长度(a) * 长度(b))
但是下面的实现效果不好。 可能是什么问题?
谢谢
代码笔: https://codepen.io/1rosehip/pen/qBrLYLo
const $box = document.getElementById('box');
const shapeRect = $box.getBoundingClientRect();
const shapeCenterX = shapeRect.x + shapeRect.width / 2;
const shapeCenterY = shapeRect.y + shapeRect.height / 2;
/**
* get vector magnitude
* @param {Array.<number>} v
* @return {number}
*/
const length = v => {
return Math.sqrt(v[0] ** 2 + v[1] ** 2);
};
/**
* dot product
* @param {Array.<number>} v1
* @param {Array.<number>} v2
* @return {number}
*/
const dot = (v1, v2) => {
return v1[0] * v2[0] + v1[1] * v2[1];
};
/**
* handle rotation
*/
document.addEventListener('mousemove', (evt) => {
// vector #1 - shape center
const centerVector = [shapeCenterX, shapeCenterY];
const centerVectorLength = length(centerVector);
// vector #2 - mouse position
const mouseVector = [evt.pageX, evt.pageY];
const mouseVectorLength = length(mouseVector);
// cos(angle) = dot(a, b) / (length(a) * length(b))
const radians = Math.acos(dot(centerVector, mouseVector) / (centerVectorLength * mouseVectorLength));
const degrees = radians * (180 / Math.PI);
const angle = (degrees + 360) % 360;
$box.style.transform = `rotate(${degrees}deg)`;
});
#box{
position: absolute;
background: #111;
left: 100px;
top: 100px;
width: 100px;
height: 100px;
}
<div id="box"></div>
【问题讨论】:
标签: javascript rotation angle dot-product