Point DIV at Another DIV (Angle Between Two Points)
const dot = document.createElement('div')
Object.assign(dot.style, {
position: 'absolute',
left: '100px',
top: '100px',
width: '10px',
height: '10px',
transform: 'translate(-5px, -5px)',
background: 'black'
});
document.body.appendChild(dot);
const pointer = document.createElement('div');
Object.assign(pointer.style, {
position: 'absolute',
left: '-10px',
top: '-5px',
width: '20px',
height: '10px',
background: 'red'
});
document.body.appendChild(pointer);
// desktop only (`touchmove` needed for mobile)
document.addEventListener('mousemove', (e) => {
const dx = parseFloat(dot.style.left) - e.clientX;
const dy = parseFloat(dot.style.top) - e.clientY;
const angle = Math.atan2(dy, dx) / Math.PI * 180;
pointer.style.transform = `
translate(${e.clientX}px, ${e.clientY}px)
rotate(${angle}deg)
`;
});
Moving your mouse around the page, you’ll notice the red div
always points at the black div
.
(more…)