A
A
antpv2018-08-02 18:48:35
css
antpv, 2018-08-02 18:48:35

How to find out cursor deg in JS relative to some conditional point?

In order not to write a lot of text, I made an illustration
5b632727817e3770982739.png
I am not very friendly with geometry, I will be glad for hints or formulas that can give deg using the X && Y positions of the cursor and target :)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Stalker_RED, 2018-08-02
@antpv

deg mean angle? An angle is measured between two straight lines, not two points. You need at least three points.
oBPKzx.png

let rad = Math.atan2(P3.y - P1.y, P3.x - P1.x) -
            Math.atan2(P2.y - P1.y, P2.x - P1.x)
            
  display.value = rad * (180 / Math.PI)

jsfiddle.net/72cLse6z

R
Ridz, 2018-08-02
@Ridz

<!DOCTYPE html>
<html>
<head>
  <title>Untitled</title>
  <style type="text/css">
  body {
      position: relative;
  }

  .target  {
  position: absolute;
  top: 190px; left: 190px;
  width: 60px; height: 60px;
  border-radius: 50%;
  background-color: red;
  text-align: center;
  line-height: 60px;
  color: #FFFFFF;
  }

  .line {
  position: absolute;
  top: 220px;
  left: 220px;
  width: 100px;
  height: 4px;
  background-color: red;
  transform-origin: 0;
  }

  </style>
  <script>
  document.addEventListener('DOMContentLoaded', function() {
    const target = document.querySelector('.target');
    const line = document.querySelector('.line');
    const pos = {left : 190, top : 190, width : 60, height : 60};
    const lft = pos.left + pos.width / 2;
    const tp = pos.top + pos.height / 2;
    document.addEventListener('mousemove',
    function(event) {
               let x = event.pageX - lft - 8;
               let y = event.pageY - tp - 8;
               let r = Math.sqrt(x * x + y * y);
               let deg = 180 / Math.PI * Math.atan2(y, x);
               if(deg < 0) deg += 360;
               target.innerHTML = (deg|0) + ' deg'
               line.style.transform = "rotate(" + deg + "deg)";
               line.style.width = r + 'px'

    })
  });
  </script>
</head>
<body>
  <div class="line"></div>
  <div class="target"></div>
</body>
</html>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question