Element after translation goes back to origin place?

I posted before but there was a lot of code that I changed but the issue is the same. I am trying to translate an element after the mouse moves. here’s the code:

<svg id="m" width="40" height="40">
        <circle cx="20" cy="20" r="20" fill="red" stroke="red" stroke-width="1"/>
    </svg>
    
    <script>
let m = document.getElementById("m");
 
let start = function(e) {
  var speedX = Math.abs(e.movementX);
  var speedY = Math.abs(e.movementY);
  
  m.style.transform = `translate(${speedX}px, ${speedY}px)`;
};
 
document.addEventListener("mousemove", e => start(e));
    </script> 

and I was wondering how to add direction too, but only after fixing this problem. thanks a lot

Answer

You are equalizing the position, to the current movement.

What you want is to add the movement (not absolute values) to the current position.

Remember: position = position + velocity.

You can also improve the behavior, by moving it just when clicking, to avoid it to get out of the screen and making undesired movements.

E.g.:

let m = document.getElementById("m");
let posX = 0;
let posY = 0;

let update = function(e) {
  posX += e.movementX;
  posY += e.movementY;

  m.style.transform = `translate(${posX}px, ${posY}px)`;
};

// Listen to movement when mousedown.
document.addEventListener("mousedown", () => {
  document.addEventListener("mousemove", update);
});

// Remove movement when mouseup.
document.addEventListener("mouseup", () => {
  document.removeEventListener("mousemove", update);
});
<svg id="m" width="40" height="40">
  <circle cx="20" cy="20" r="20" fill="red" stroke="red" stroke-width="1"/>
</svg>

Leave a Reply

Your email address will not be published. Required fields are marked *