I’m almost there with this –
Looking to create a small circle that moves around the border of a larger circle on mouse move. I have the following but the small circle doesn’t stay within the confines of the parent outer circle, although the movement is correct.
Codepen: https://codepen.io/Katharine-Mills/pen/jOoVJqa
Thank you!
Tried the below:
The result was that the small inner circle moves to the bottom right of the outer circle rather than following along the border.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Large Circle with Small Circle</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
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;
}
</style>
</head>
<body>
<div class="container">
<div class="circle outer-circle" id="outerCircle">
<div class="inner-circle" id="innerCircle"></div>
</div>
</div>
<script>
$(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 });
});
});
</script>
</body>
</html>
Katharine Mills is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.