Web Platform Javascript

Math and Geometry Quick Reference

Angles

Convert between degrees and radians:

function degreesToRadians(deg) {
    return deg * Math.PI / 180;
}

function radiansToDegrees(radians) {
    return radians * 180 / Math.PI;
}

Angle (in radians) between two coordinates:

function angle(x1, y1, x2, y2) {
    return Math.atan2(
        y1-y2,
        x1-x2
    );
}

Get an x,y coordinate in relation to distance and angle to another point. This can be useful for plotting something on a circle.

function polarToCartesian(radians, distance, x, y) {
  return {
      x: distance*Math.cos(radians) + x,
      y: distance*Math.sin(radians) + y
  }
}

Value changing

Keeps track of a value and 'bounces' it between low and high bounds. This can be useful for animation.

function valueBounce(low, high, incr) {
  let current = low;
  return function() {
    if (current > high || current < low) incr *= -1.0;  
    current += incr;
    return current;
  }
}

eg: create a function that bounces between 0-100, incrementing/decrementing by 1

let xBounce = valueBounce(0, 100, 1);

Once you've set it up, repeatedly call xBounce() when you want the value to change:

let x = xBounce();

Random

Math.random() returns a value between 0 and (but not including 1). Eg: 0.4, 0.2, 0.7, 0.0 and so on.

To get a quick random number between 0 and max, multiply the random value and max. For example, to get a random number between 0 and the width of the canvas:

let x = Math.random() * canvas.width;

From Math.random

// Returns a random whole number between min and max
// Range includes min value but excludes max
function randomInt(max, min = 0) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min)) + min;
}

function random(max, min = 0) {
  return Math.random() * (max - min) + min;
}