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. 
I remember learning this from nooflat.nu by Jamie Macdonald back in 2001-2. I spun up my custom made experimental browser to take a look… also downloaded the source…
Excuse the music I was too lazy to open iMovie and add something decent… Here is the key part of the source where I learned about atan2 for the first time đ
- //SOURCE FOR EDUCATIONAL PURPOSES, ETC.
- fscommand("allowscale","false") 
- // FUNCTION TO CALCULATE ANGLE FROM ONE OBJECT TO ANOTHER
- function calcangle (me,targetclip) { 
- // FIRST COMPUTE THE DISTANCES FROM THE MOVIECLIP THE FUNCTION
- // IS CALLED FROM TO THE TARGET CLIP:
- var deltax = me._x-targetclip._x; 
- var deltay = me._y-targetclip._y; 
- // NEXT USE THESE DISTANCES TO CALCULATE THE ANGLE BETWEEN THEM:
- angle = Math.atan2(deltay, deltax); 
- // FINALLY CONVERT THE ANGLE FROM RADIANS TO DEGREES AND THEN RETURN THE RESULT:
- angle /= (Math.pi/180); 
- return angle; 
- }
Brings back great memories…