To start, you grab the canvas element itself and set a 2D context on it like this:
All our work is now going to be done on our new variable c.
To start drawing something, HTML canvas elements have a beginPath() method that indicates you’re about to start drawing.
The arc() method is what we’ll actually use to draw our circles and it takes at least 5 parameters:
- The x-coordinate of the centre of the circle
- The y-coordinate of the centre of the circle
- The radius of the circle
- The starting angle of the circle
- And the ending angle of the circle
So our arc() method ends up looking like this:
And finally, we can finish off with either a stroke() method or a fill() method. I’ve gone for fill:
We can customise our fill or stroke using fillStyle and strokeStyle respectively.
And now we have a circle in the centre of our canvas element:
We only have one circle in our canvas element but we want more circles, so lets wrap our code in a function and use a for loop to draw 50 circles:
You may notice that our HTML doesn’t show anything new, but that’s because they are all being drawn on top of each other. So we need a way to randomise our x and y coordinates. We can easily fix this by editing the first two parameters in our arc method like this:
And that seems to have pretty much fixed that issue. But we still need our custom colour-way.
Having started out in Ruby I noticed that I took a lot of it’s built-in methods for granted. The ability to select a random element from an array using .sample is a luxury not yet available in JavaScript. Of course, there is still a solution – which could probably fit in one line of code – but it took me a little while to make sense of it.
Here I have an array of colours (https://color.adobe.com/explore) and want to randomly assign each sphere a random colour within the array. We can easily achieve this by doing this:
The Math.random() function returns a value between 0 (inclusive) and 1 (exclusive). We times that by the array length (which, in this case, is 5) meaning that now we get a random value between 0 and 4.9999999…
Now, to even out our decimal places we wrap all of that in a Math.floor() function. Doing this will give us a value of either 0, 1, 2, 3, or 4. You may use the Math.ceil() function in another situation (so you would get ‘truthy’ values of 1 to 5), and you may have thought to use it in this situation – but it’s not ideal. And that’s because array indexes are zero-based. We are trying to access a random index of the array.
So now that we have a reusable method that lets us access random values in an array, we can set our fillStyle to a random value in our ‘colours’ array:
And we get our field of random circles: