This sketch uses p5.js, a javascript library that makes it easy to draw graphics on an webpage. The shapes are drawn on a coordinate system measured in pixels. As you can see on the right, the origin (0,0) of the grid is in the upper-left hand corner.
To draw a custom shape, you begin with the beginShape()
function, then define the (x,y) coordinates of the vertices of your shape. p5 connects the points for you.
For example, the following code will draw a square, as seen on the right:
beginShape();
vertex(100, 100);
vertex(100, 200);
vertex(200, 200);
vertex(200, 100);
endShape(CLOSE);
Code Slang calculates these vertices by passing an array of points through several slang functions. These functions perform mathematical operations on each number.
Without the slang functions, the points are equal and the base shape is just a circle. This is because we use sine and cosine to calculate the (x,y) coordinates of the vertices:
beginShape();
points.forEach((point,angle) => {
let x = point * Math.cos(radians(angle));
let y = point * Math.sin(radians(angle));
vertex(x, y);
})
endShape();
If you manually change the numbers in points
, the circle will change shape accordingly.
The slang functions codify these changes to the numbers in the points
array.
For example, multiplying each point by 2 would double the size of the circle. Using the map
function, we can easily loop over each point in points
:
points.map(point => point * 2)
We can get much more interesting results by using math functions. A few functions to try are:
Math.cos()
Math.tan()
Math.sin()
Math.abs()
Math.log()
Math.random()
See what they do individually, and then try combining them. For example: points.map((point, angle) => point * Math.abs(Math.cos(angle * 3))))