我想在一个圆圈(红色圆圈)内制作一个浮动元素(白色圆圈),如下所示。但是,如果您将元素移近圆的角,则元素会超出圆的边界。
如何对元素进行约束,使其不超出外圈?
PS我尝试应用一个单位圆,找到了外圆中心到元素当前位置的距离,如果这个距离大于1,那么它并没有改变元素的位置,但这导致到元素的阻塞(不再移动)。
const
stick = document.querySelector("#stick"),
stickWidth = stick.clientWidth,
stickHeight = stick.clientHeight,
stickArea = stick.parentNode,
stickAreaWidth = stickArea.clientWidth,
stickAreaHeight = stickArea.clientHeight
stick.style.left = (stickAreaWidth - stickWidth) / 2 + 'px'
stick.style.top = (stickAreaHeight - stickHeight) / 2 + 'px'
stick.onmousedown = function(event) {
event.preventDefault();
let shiftX = event.clientX - stick.getBoundingClientRect().left;
let shiftY = event.clientY - stick.getBoundingClientRect().top;
document.addEventListener('mousemove', onMouseMove);
document.addEventListener('mouseup', onMouseUp);
function onMouseMove(event) {
let
newLeft = event.clientX - shiftX - stickArea.getBoundingClientRect().left,
newTop = event.clientY - shiftY - stickArea.getBoundingClientRect().top,
rightEdge = stickAreaWidth - stickWidth,
topEdge = stickAreaHeight - stickHeight,
dataStick = getDataStick(stick);
if (newLeft < 0) newLeft = 0;
if (newTop < 0) newTop = 0;
if (newLeft > rightEdge) newLeft = rightEdge;
if (newTop > topEdge) newTop = topEdge;
// if (dataStick.distance > 1) {
// return
// }
stick.style.left = newLeft + 'px';
stick.style.top = newTop + 'px';
}
function onMouseUp() {
document.removeEventListener('mouseup', onMouseUp);
document.removeEventListener('mousemove', onMouseMove);
}
};
stick.ondragstart = function() {
return false;
};
function getDataStick(stick) {
const
parentPos = stick.parentNode.getBoundingClientRect(),
stickPos = stick.getBoundingClientRect(),
x = (parentPos.left - stickPos.left) / (stick.parentNode.clientWidth - stick.clientWidth) * (-2) - 1,
y = (parentPos.top - stickPos.top) / (stick.parentNode.clientHeight - stick.clientHeight) * 2 + 1,
data = {}
data.x = x
data.y = y
data.distance = (Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2))).toFixed()
return data
}
body {
width: 100vw;
height: 100vh;
font-size: 16px;
margin: 0;
display: flex;
align-items: center;
justify-content: center;
background-color: #212529;
box-shadow: inset 0 0 5rem rgba(0, 0, 0, 0.5);
}
.wrapper {
width: 90vw;
height: 90vw;
max-width: 300px;
max-height: 300px;
position: relative;
display: flex;
justify-content: space-around;
background: brown;
border-radius: 50%;
}
#stick {
width: 100px;
height: 100px;
border-radius: 50%;
position: absolute;
background-color: white;
cursor: pointer;
}
<div class="container">
<div class="wrapper">
<div id="stick"></div>
</div>
</div>
老实说,我重写了您的代码,很难弄清楚。希望你不要被冒犯。
但一切正常:
如果你想减少到中心的最大距离,就在这里:
在检查中,不要使用stickAreaRad,而是你需要的半径。希望它有所帮助。