Как повернуть объект относительно точки?

Есть объект, есть его координаты - x и y. Как повернуть его на r градусов относительно центра с координатами x2 и y2?


Ответы (1 шт):

Автор решения: Alexander Lonberg

Примерно так:

const line = document.getElementById('line')
const center = (() => {
  const { left, width, top, height } = line.getBoundingClientRect()
  return { left: left + width / 2, top: top + height / 2 }
})()

document.addEventListener('mousemove', ({ clientX, clientY }) => {
  const deg = Math.atan2(center.top - clientY, center.left - clientX) * (180 / Math.PI)
  line.style.transform = `rotate(${deg}deg)`
})
body {
  margin: 0;
  padding: 0;
  width: 100vw;
  height: 100vh;
  color: gray;
}

#line {
  width: 100px;
  height: 4px;
  background-color: red;
  border-radius: 2px;
  display: block;
  position: absolute;
  top: 60px;
  left: 10px;
}

.center {
  display: block;
  width: 8px;
  height: 8px;
  border-radius: 4px;
  position: absolute;
  left: 46px;
  top: -2px;
  background-color: black;
}
<h3>Верти мышкой</h3>
<div id="line" style="transform: rotate(0deg);"><span class="center"></span></div>

→ Ссылка