Хочу создать маленький круг, который будет перемещаться вокруг границы большего круга при перемещении мыши. У меня есть следующее, но маленький круг не остается в пределах родительского внешнего круга, хотя движение правильное.
Codepen: https://codepen.io/Katharine-Mills/pen/jOoVJqa
Попробовал следующее:
В результате маленький внутренний круг перемещается в правый нижний угол внешнего круга, а не следует вдоль границы.
Код: Выделить всё
$(document).ready(function() {
const outerCircle = $('#outerCircle');
const innerCircle = $('#innerCircle');
const outerCircleRadius = outerCircle.width() / 2;
const innerCircleRadius = innerCircle.width() / 2;
// Update inner circle position based on mouse movement on the screen
$(document).on('mousemove', function(event) {
const containerX = outerCircle.offset().left;
const containerY = outerCircle.offset().top;
const centerX = containerX + outerCircleRadius;
const centerY = containerY + outerCircleRadius;
const mouseX = event.clientX;
const mouseY = event.clientY;
// Calculate the angle between the mouse and the center of the outer circle
const angle = Math.atan2(mouseY - centerY, mouseX - centerX);
// Calculate the position of the inner circle on the outer circle's circumference
const innerCircleX = centerX + Math.cos(angle) * (outerCircleRadius - innerCircleRadius);
const innerCircleY = centerY + Math.sin(angle) * (outerCircleRadius - innerCircleRadius);
// Set the position of the inner circle
innerCircle.css({
left: innerCircleX - innerCircleRadius,
top: innerCircleY - innerCircleRadius
});
});
});Код: Выделить всё
body {
margin: 0;
overflow: hidden;
background-color: #f0f0f0;
font-family: Arial, sans-serif;
}
.container {
position: relative;
width: 100vw;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
.circle {
width: 200px;
height: 200px;
border: 2px solid white;
border-radius: 50%;
position: relative;
}
.inner-circle {
width: 20px;
height: 20px;
border-radius: 50%;
background-color: white;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.outer-circle {
width: 300px;
height: 300px;
border: 2px solid white;
border-radius: 50%;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
overflow: hidden;
}Код: Выделить всё
Подробнее здесь: https://stackoverflow.com/questions/785 ... mouse-move
Мобильная версия