JavaScript Miscellanea
Technical details that get in the way instead of helping go here. What’s p5.js? How to orient the canvas? Etc.
Contents:
Prerequisites
I’ll be assuming throughout this blog that you know a bit of coding, just the basic concepts:
- variables
- flow control
- functions
If that doesn’t mean anything to you, maybe come back here later. The Coding Train is a good place to start learning JavaScript, but it doesn’t really matter which language you learn, the knowledge is transferable.
p5.js
p5.js is a framework focused on “on making coding accessible”. For me, that means I can write cool interactive visualizations (sketches, as they are called), with code that’s basically self explanatory. Check it out:
Edit the code a bit and run it again. Try changing the second line to createCanvas(200, 100)
with 100
instead of 200
at the end. Also give background(110)
a go. You can always check the official reference to find out how something works exactly.
We use the setup
function to create and, well, setup the canvas, but if we want something dynamic, we need to add a draw
function: p5.js calls it repeatedly for as long as this page is open in your browser.
Can you guess what mouseX
does? This is what sold me on p5.js. There’s plenty other ways to interact with the sketch, and they’re all just as easy! This tutorial is a good place to read about them.
Drawing a Cartesian plane
You can imagine that using the canvas to draw points in a Cartesian plane will be useful in a blog about math. Unfortunately for me, the creators of p5.js followed the HTML standards when choosing default settings. I specifically don’t enjoy their answers to the following questions:
- Where is the origin?
“top-left.”
- In which way are the axes directed?
“to the right and down.”
The result is that (x,y)
of p5.js is not my \((x,y).\) Let me show you this by drawing a circle of radius 50 pixels around (0,0).
What I expect to see, given that we start out with
\[(x,y) = 50\cdot(\cos(0),\sin(0)) = (50,0)\]and increase the angle inside the trig functions slowly, is a circle going counterclockwise in the middle of the canvas. Obviously, the result is quite different than what I had in mind. Luckily, we have a quick fix for that: add the following code to draw
right before point(x,y)
and run it again.
plotly.js
p5.js gives you the ability to draw anything you want on the canvas super easily, but sometimes you might want to plot a function without any boilerplate code. In those cases I use plotly.js. It does require working just a bit behind the scenes of this webpage though.
Try it yourself: