)
}
}
)
(
}
{
)
)
(
)
(
(
{
}
)
(
)
}
)
)
{
(
(
)
)
}
)
(
}

Point DIV at Another DIV (Angle Between Two Points)

  1. const dot = document.createElement('div')
  2. Object.assign(dot.style, {
  3.   position: 'absolute',
  4.   left: '100px', 
  5.   top: '100px',
  6.   width: '10px', 
  7.   height: '10px',
  8.   transform: 'translate(-5px, -5px)',
  9.   background: 'black'
  10. });
  11. document.body.appendChild(dot);
  12.  
  13. const pointer = document.createElement('div');
  14. Object.assign(pointer.style, {
  15.   position: 'absolute',
  16.   left: '-10px', 
  17.   top: '-5px',
  18.   width: '20px', 
  19.   height: '10px',
  20.   background: 'red'
  21. });
  22. document.body.appendChild(pointer);
  23.  
  24. // desktop only (`touchmove` needed for mobile)
  25. document.addEventListener('mousemove', (e) => {
  26.   const dx = parseFloat(dot.style.left) - e.clientX;
  27.   const dy = parseFloat(dot.style.top) - e.clientY;
  28.   const angle = Math.atan2(dy, dx) / Math.PI * 180;
  29.  
  30.   pointer.style.transform = `
  31.     translate(${e.clientX}px, ${e.clientY}px)
  32.     rotate(${angle}deg)
  33.   `;
  34. });

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 😀

  1. //SOURCE FOR EDUCATIONAL PURPOSES, ETC.
  2. fscommand("allowscale","false")
  3.  
  4.  
  5. // FUNCTION TO CALCULATE ANGLE FROM ONE OBJECT TO ANOTHER
  6. function calcangle (me,targetclip) {
  7.  
  8. 	// FIRST COMPUTE THE DISTANCES FROM THE MOVIECLIP THE FUNCTION
  9. 	// IS CALLED FROM  TO THE TARGET CLIP:
  10. 	var deltax = me._x-targetclip._x;
  11. 	var deltay = me._y-targetclip._y;
  12.  
  13. 	// NEXT USE THESE DISTANCES TO CALCULATE THE ANGLE BETWEEN THEM:
  14. 	angle = Math.atan2(deltay, deltax);
  15.  
  16. 	// FINALLY CONVERT THE ANGLE FROM RADIANS TO DEGREES AND THEN RETURN THE RESULT:
  17. 	angle /= (Math.pi/180);
  18. 	return angle;
  19. }

Brings back great memories…

snippet.zone ~ 2021-24 /// {s/z}