所以我正在尝试一些js和数学..我想创建一个x,y轴和一条根据鼠标位置旋转的线,并且我希望它根据距我的原点或中心的距离增加其高度轴..现在,当我尝试增加 div 的高度时..它会向下移动,而每当我尝试减少其高度时,它就会向上移动..我该如何解决这个问题??
let x = document.body.clientWidth / 2;
let y = ( document.body.clientHeight || document.documentElement.clientHeight ) / 2;
let ang = document.querySelector(".angle");
document.addEventListener("mousemove",(e)=>{
let thetaRadians = Math.atan2(e.clientY - y, e.clientX - x);
let thetaDegrees = thetaRadians * (180 / Math.PI);
ang.style.rotate = `${thetaDegrees + 90}deg`;
const distance = Math.floor(Math.sqrt(Math.pow((e.clientX - x),2) + Math.pow((e.clientY - y),2)));
ang.style.height = `${distance}px`;
});
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html, body {
height: 100%;
width: 100%;
}
body {
display: flex;
align-items: center;
justify-content: center;
}
.line {
height: 75%;
width: 2px;
background: #000;
position: absolute;
}
.line::before {
content: '';
position: absolute;
height: 100%;
width: 100%;
background: #000;
rotate: 90deg;
}
.angle {
height: 190px;
rotate: 45deg;
transform-origin: bottom;
width: 2px;
background: red;
}
<div class="line">
<div class="angle"></div>
</div>
看起来您正在尝试将红线
.angle
定位为从原点开始。但是,目前没有任何东西可以将 .angle
从其父元素顶部的默认位置向下移动。
您当前从图表顶部沿 y 轴绘制线条,然后绕其底端点旋转。因此,如果光标落在由轴长度定义的圆上,则线条仅从原点开始。
如果您想继续以这种方式绘制它,从图表的顶部开始,除了旋转它之外,您还需要从其初始位置平移(移动)
.angle
。但如果一开始就根据原点画线会更容易。
实现此目的的一种方法是始终将线置于图形原点的中心并在那里旋转,同时使用 CSS 渐变隐藏一半。这样您就不必担心平移直线,我们只需要围绕中心进行简单的旋转,您已经实现了这一点。
const lineElement = document.querySelector(".line")
document.addEventListener("mousemove", (e) => {
const graphBounds = document.querySelector(".graph").getBoundingClientRect()
const originX = graphBounds.left + graphBounds.width / 2
const originY = graphBounds.top + graphBounds.height / 2
const thetaRadians = Math.atan2(e.clientY - originY, e.clientX - originX);
const thetaDegrees = thetaRadians * (180 / Math.PI);
lineElement.style.rotate = `${thetaDegrees + 90}deg`;
const lineLength = Math.round(
Math.sqrt(
Math.pow((e.clientX - originX), 2) +
Math.pow((e.clientY - originY), 2)
)
);
// Line length needs to be doubled as half of the line is hidden
lineElement.style.height = `${lineLength * 2}px`;
});
body {
margin: 0;
padding: 0;
overflow: hidden;
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
}
.graph {
width: 75vh;
height: 75vh;
display: flex;
align-items: center;
justify-content: center;
}
.axis {
background: #000;
width: 2px;
height: 100%;
}
.axis-x {
rotate: 90deg;
}
.line {
/* Line is centered on the origin but the first half is transparent */
background: linear-gradient(0, transparent 0 50%, red 50% 100%);
width: 2px;
margin-left: -2px;
}
<div class="graph">
<div class="axis axis-x"></div>
<div class="axis axis-y"></div>
<div class="line"></div>
</div>