Aspect Ratio Calculator
By Caleb Trevatt • 3 minutes read •
Why?
I threw this together for two reasons:
- Aspect ratio is tedious to calculate by hand.
- 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:
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…
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 linerif/else
statement.
- If
b
is0
, it returnsa
(base case). - Otherwise, it calls itself recursively with
b
anda % b
untilb
becomes0
, at which pointa
is theGCD
.
;
;
;
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
Layout: Not a fan of the default view. I like the results on the right and the HTML, CSS, JS stacked on the left.
Ducks in a row: Indentation seems quirky. Alignment always seems to overshoot on the first tab.
Brainrot: I was hankering for my IDE and AI code completion… Maybe more of a comment on me than CodePen.
Activation Energy: I wouldn’t have bothered with this if I had to start a git repo, create a project, spin up a web server, etc. How much learning have I missed because I haven’t throw together junky tools with rapid prototyping?