Search code examples
javascriptcanvasradians

How to alter a degree value into an actual x/y position change?


Im drawing a circle on html canvas, the circle is meant to indicate a "ship".

I have the current position (x, y) of the "Ship" object and randomly determine a degree (0 to 360) and an amount value. I then want to alter the ship's current position by the degree and amount.

i.E. ship is currently at 100/100 (on a canvas). I determine degree as 30 and amount as 50.

Now i would like to get the ships new location based on the assumption that 0 degree would indicate "straight up" and 180 degree would indicate straight down while 50 amount indicate a movement of 50 Pixels into the direction determined.

I know it has something to do with Radians, but unfortunally im unable to solve it further.

var ship = {
  x: 100,
  y: 100
}

var movement = {
  degrees: 30,
  amount: 50
}

Solution

  • Yes, all angles in JavaScript are in radians. In addition, the canvas context has 0° point to the right so you need to subtract 90° from all angles if you want 0° to be straight up:

    var angle = (movement.degrees - 90) / 180 * Math.PI;  // compensate angle -90°, conv. to rad
    ship.x += movement.amount * Math.cos(angle);          // move ship
    ship.y += movement.amount * Math.sin(angle);
    

    var movement = {
      degrees: 30,
      amount: 50
    }
    
    var ctx = document.querySelector("canvas").getContext("2d");
    
    (function loop() {
      ctx.clearRect(0, 0, 300, 150);
    
      var ship = {  // reset ship position for demo
        x: 100,
        y: 90
      }
    
      ctx.strokeRect(ship.x - 2, ship.y - 2, 4, 4);
      ctx.fillText("From", ship.x + 5, ship.y);
    
      var angle = (movement.degrees - 90) / 180 * Math.PI; // compensate angle -90°, conv. to rad
      ship.x += movement.amount * Math.cos(angle); // move ship
      ship.y += movement.amount * Math.sin(angle);
    
      ctx.strokeRect(ship.x - 2, ship.y - 2, 4, 4);
      ctx.fillText(movement.degrees + "°", ship.x + 5, ship.y);
      
      movement.degrees++;
      movement.degrees = movement.degrees % 360;
      requestAnimationFrame(loop);
    })();
    <canvas></canvas>