<svg id="svg" xmlns="http://www.w3.org/2000/svg" width="100%" height="100%">
<rect id="mouse-follower" rx="10"/>
</svg>
html, body {
margin: 0;
height: 100%;
}
svg {
position: absolute;
top: 12.5%;
left: 12.5%;
width: 75%;
height: 75%;
outline: 1px dashed gray;
}
const state = {
x: 0, y: 0,
w: 100, h: 100
};
const svg = document.getElementById('svg');
const follower = document.getElementById('mouse-follower');
follower.setAttribute('width', state.w);
follower.setAttribute('height', state.h);
document.addEventListener('mousemove', onMouseMove);
function onMouseMove(e) {
const svgRect = svg.getBoundingClientRect();
state.x = (e.clientX - svgRect.x) - state.w / 2;
state.y = (e.clientY - svgRect.y) - state.h / 2;
follower.setAttribute('x', state.x);
follower.setAttribute('y', state.y);
const isOverflow = (
(state.x < 0) ||
(state.y < 0) ||
(state.x + state.w > svgRect.width) ||
(state.y + state.h > svgRect.height)
);
if (isOverflow) {
follower.setAttribute('fill', 'red');
}
else {
follower.setAttribute('fill', 'green');
}
}
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.