Aspect Ratio Calculator

By Caleb Trevatt3 minutes read

Why?

I threw this together for two reasons:

  1. Aspect ratio is tedious to calculate by hand.
  2. I wanted to try using CodePen.

Tedium

To calculate aspect ratio, you need the Greatest Common Divisor (GCD). You can get this with the Euclidean algorithm, but doing this by hand or in a phone calculator is still slow and manual.

You can side-step GCD by using N:1 aspect ratio instead, e.g. “1.85:1”

Just divide. 1920/1080 == 1.85

But unless you’re a cinephile, that’s not as common and probably not what you’re looking for.

CodePen

Anyway. Code to the rescue!

See the Pen Aspect Ratio Calculator by Caleb Trevatt (@in03) on CodePen.

How?

Check out the source code.

I initially did this in Python which was very easy with the function built into the standard library:

from math import gcd

Then I wanted to publish it to my site, so I moved it to Javascript. Unfortunately JS doesn’t have a GCD function built in…

function gcd(a, b) {
    return b === 0 ? a : gcd(b, a % b);
}

This is a recursive function implementing the Euclidean algorithm to find the greatest common divisor of two numbers.

Note

If you’re unfamiliar with that questionmark / colon syntax, that’s a ternary operator. It’s essentially a one liner if/else statement.

  1. If b is 0, it returns a (base case).
  2. Otherwise, it calls itself recursively with b and a % b until bbecomes 0, at which point a is theGCD.
let divisor = gcd(width, height);
let aspectWidth = width / divisor;
let aspectHeight = height / divisor;

This finds the largest number that evenly divides both width and height.

Notes on CodePen

I heard an episode of the Changelog recently interviewing Chris Coyier and Dave Rupert. Chris Coyier is the founder of Codepen and talked a little bit about it. Some of the features sounded really interesting. I threw together this junky calculator and wondered briefly about embedding it straight into my site, but I thought I’d take the opportunity to give CodePen a whirl.

I’d never actually written of my own in CodePen before, but I’ve messed around with it online when I’ve stumbled into the world of frontend demos and visual javascript experiments.

Some Key Points No One Asked For