Georg Nees’ fantastic generative art is a true inspiration. In this tutorial, we’re going to build one of his pieces: Cubic Disarray.
The only HTML we have on the page is a <canvas>
element at 320×320 pixels.
As usual, here is our initial setup. You’re not going to see anything render here, because these are the primary lines to setting up the canvas and context which we use to draw. We will also set the size of the canvas and adjust it based on the user’s device pixel ratio, or pixel density. This ensures that the final result is crisp on all monitors.
|
|
We’ve also got a variable in there to define the square size, understandably named squareSize
.
Now, let’s create a function to draw the squares. This function is going to be fairly simple, taking only a width and a height. The position of the squares is going to be handled by another loop.
|
|
So how about we draw something. I’m going to loop through and fill the screen with squares. Here we’re using the context save
, translate
& restore
functions to move the context around, and then our draw function above for drawing.
|
|
And there we have it, squares! Now we have the “cubic” part down, we can get to the disarray.
Introducing random is fairly simple: first we’ll give ourselves some variables, one for how much the squares translate out of their position, one for how much they rotate, and one for how much to offset the entire drawing to get it centered on the canvas.
|
|
We can use those variables, then, to create the random translations and rotations. They’re set up here to be larger numbers as they reach towards the end of the canvas.
|
|
Now, we apply the translations and rotations. (Suddenly all that setup paid off!)
|
|
And there we have it: cubic disarray!