I’m Having trouble to center the default mouse cursor inside a circle that follows the mouse cursor
see this image
// Create an html element and append to body
const dpkCursor = document.createElement("div");
dpkCursor.classList.add("dpkCursor");
document.body.appendChild(dpkCursor);
// Fuction that create circle to follow the cursor
function initCursor(speedOption = 0.25) {
let dpkCursorMouse = { x: -100, y: -100 };
let dpkCursorPos = { x: 0, y: 0 };
let speed = speedOption;
window.addEventListener("mousemove", (e) => {
dpkCursorMouse.x = e.x;
dpkCursorMouse.y = e.y;
});
const updatePosition = () => {
dpkCursorPos.x += (dpkCursorMouse.x - dpkCursorPos.x) * speed;
dpkCursorPos.y += (dpkCursorMouse.y - dpkCursorPos.y) * speed;
dpkCursor.style.transform = `translate(${dpkCursorPos.x}px ,${dpkCursorPos.y}px)`;
};
function loop() {
updatePosition();
requestAnimationFrame(loop);
}
requestAnimationFrame(loop);
}
initCursor()
Advertisement
Answer
Simply remove 50% from each side using
dpkCursor.style.transform = `translate(calc(${dpkCursorPos.x}px - 50%) ,calc(${dpkCursorPos.y}px - 50%))`;
const dpkCursor = document.createElement("div");
dpkCursor.classList.add("dpkCursor");
document.body.appendChild(dpkCursor);
function initCursor(speedOption = 0.25) {
let dpkCursorMouse = { x: -100, y: -100 };
let dpkCursorPos = { x: 0, y: 0 };
let speed = speedOption;
//center the circle around cursor
window.addEventListener("mousemove", (e) => {
dpkCursorMouse.x = e.x;
dpkCursorMouse.y = e.y;
});
const updatePosition = () => {
dpkCursorPos.x += (dpkCursorMouse.x - dpkCursorPos.x) * speed;
dpkCursorPos.y += (dpkCursorMouse.y - dpkCursorPos.y) * speed;
dpkCursor.style.transform = `translate3d(calc(${dpkCursorPos.x}px - 50%) ,calc(${dpkCursorPos.y}px - 50%),0)`;
};
function loop() {
updatePosition();
requestAnimationFrame(loop);
}
requestAnimationFrame(loop);
}
initCursor()body{
background:black;
}
.dpkCursor {
height: 1.75rem;
width: 1.75rem;
position: fixed;
top: 0;
left: 0;
color: white;
border: 2px solid #fff;
mix-blend-mode: difference;
border-radius: 50%;
pointer-events: none;
z-index: 999;
}
