I'm trying to make an element moves when the mouse moves in a random 340° direction excluding the 20° of the cursor so the element won't move to the cursor but when I translate It always goes back to the origin place as if there were no translating. here's the code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>SVG</title>
</head>
<body>
<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 angle = Math.floor(Math.random() * 340) * Math.PI / 180;
var timestamp, lastMouseX, lastMouseY = null;
let setCursorPosition = function(e) {
//mousespeed
if (timestamp === null) {
timestamp = Date.now();
lastMouseX = e.screenX;
lastMouseY = e.screenY;
return;
}
var now = Date.now();
var dt = now - timestamp;
var dx = e.screenX - lastMouseX;
var dy = e.screenY - lastMouseY;
var speedX = Math.round(dx / dt * 100);
var speedY = Math.round(dy / dt * 100);
timestamp = now;
lastMouseX = e.screenX;
lastMouseY = e.screenY;
//
m.style.transform = "translate(" + Math.cos(angle)*speedX + "px," + Math.sin(angle)*speedY + "px)";
};
document.addEventListener("mousemove", e => setCursorPosition(e));
</script>
</body>
</html>
thanks
also tell me if the implementation of the direction of the element is just like I wanted or no, I have a feeling that it's wrong