move elem v2

by ShaCP

HTML

<div id="container">
  <div id="one">
  <span>Hello</span>
  </div>
  </div>

CSS

#one {
  width: 100px;
  height: 100px;
  background-color: lightskyblue;
  position: relative;
  animation: 3s linear forwards;
  /* margin-top: 100px; */
  writing-mode: vertical-lr;
  text-orientation: upright;
  letter-spacing: -1px;
  user-select: none;
}

body {
  margin: 0;
  width: 100vw;
  height: 100vw;
}

#one.play {
  animation-name: move;
}

@keyframes move {
  from {
    transform: rotate(360deg);
  }
}

#container {
  border: 1px solid;
  width: max-content;
  position: relative;
  top: 25%;
  left: 50%;
}

JavaScript

/* one.addEventListener("click", (e) => {
  e.target.classList.toggle("play");
  e.target.classList.remove("off");
})

one.addEventListener("animationend", (e) => e.target.classList.toggle("play")) */

/* one.addEventListener("animationstart", (e) => {
  if (e.animationName === "move-text") {
    window.requestAnimationFrame(step);
  }
}) */

const divElem = document.querySelector('div');

let coordinates = getCoords(one);
let lastMousePosition = {};
let elementPosition = {x: 0, y: 0}; 

const moveElement = evt => {
	const {pageX, pageY} = evt;
  
	const Xoffset = pageX - lastMousePosition.pageX;
  const Yoffset = pageY - lastMousePosition.pageY;
  
  elementPosition.x += Xoffset;
  elementPosition.y += Yoffset;
  lastMousePosition = {pageX, pageY};
  
  const anim = one.animate({
    transform: `translate(${elementPosition.x}px, ${elementPosition.y}px)`,
    backgroundColor: "red"
  }, {
    duration: 250,
    fill: 'forwards',
    easing: "linear"
  });

  anim.commitStyles();
}

const moveElementSetup = evt => {
	const {pageX, pageY} = evt;
  lastMousePosition = {pageX, pageY};
  document.body.addEventListener('mousemove', moveElement);
}

const removeMoveEventHandler = evt => {
  document.body.removeEventListener('mousemove', moveElement);
}

document.addEventListener('mouseup', removeMoveEventHandler);
one.addEventListener('mousedown', moveElementSetup);


function getCoords(elem) {
  let box = elem.getBoundingClientRect();
  /* I need to add the page offset because the bounding rectangle
  coordinates are based on the viewport, not the page. So, for example,
  if the element is positioned to that its bottom is sitting at the top of
  the viewport, meaning it's scrolled out of view, then the coordinates
  of the bottomo would be 0, the start of the viewport. pageOffset gives you
  the amount of pixels the page has been scrolled
  */
  return {
    top: box.top + window.pageYOffset,
    right: box.right + window.pageXOffset,
    bottom: box.bottom +...