The Joy Division album cover has a cool history, and is a beautiful example of data driven art. In this tutorial we’re going to recreate it in a more simplistic form.
We’re going to do this with the JavaScript canvas. No extra APIs. The only HTML we have on the page is a <canvas>
element at 320×320 pixels.
Let’s kick things off with some 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.
|
|
This gives us access to the context
which allows us to draw on the page.
Our initial plan of attack here is to create the lines on the canvas, which will be a series of points. From there, we will start to displace the points randomly to give us the effect we desire.
Let’s get some base variables in here: step
, which will be the steps in pixels between our points, and an array called lines
, which is going to hold our lines.
|
|
Now we’ll write a function to prepare our lines. A line will consist of a series of points with x
and y
properties.
|
|
Our next step will be to draw these lines. Again, we’ll start simple to get something on the page, and we will expand on it later.
|
|
Amazing, we have lines on our canvas! Now, the next job we have is to displace them. We will do that up in our first loop, where we create the points.
|
|
Ahh, there we have it. Our lines are now jumping all over the place, just as planned. The next step is to get them to distort in the areas that we want—namely, more distorted towards the center, and less towards the edges. We are going to do this with an absolute function.
|
|
We can see here that we’ve made something a little messy and that we can see through each line, which doesn’t look great. We’re going to use a fill
with a globalCompositeOperation
of destination-out
to fix this.
Global composite operations allow us to draw to the canvas in very interesting ways. For our case, we want to essentially “erase” our new shape from the existing lines above it. The destination-out
mode works great for erasing from a canvas. Check out this article to learn more about canvas global composite operations.
|
|
We’re getting so close now. The only piece left is to make the lines much less jagged. To do this, we’re going to use quadratic curves, and create control points between each one to create a smooth path. The final quadraticCurveTo
is the last joining step.
|
|
This looks great! Now we just need a little breathing room on top. Let’s prevent the top lines from going off the top of the canvas. We can do this by starting the loop at a higher index to skip the drawing of a few of the top lines.
|
|
And there we have it! You can mess with the steps, and styles and colors for a bunch of different results. All are exciting!