We’ll start from scratch. So, create a new HTML document using your favorite text-editor, and add the HTML5 boiler-plate code to it.
<body>, add a
<canvas> whose width and height are 700px and 600px respectively. Feel free to use other dimensions, if you want to.
Next, create a
<script> tag, and get a reference to the canvas using the
getElementById() method of the
Finally, get a reference to the 2D context of the canvas, by calling its
The canvas is now ready.
One of the easiest ways to generate a Koch Curve is to use a Thue-Morse sequence, which is just a sequence containing zeroes and ones. It starts with a
0 and the rest of the digits are determined using the following algorithm:
The first few digits look like this: 01101001…
As you can see, with every iteration, the size of the sequence doubles. Therefore, you must try and keep the number of iterations low.
Here’s the code I’ll be using to generate the sequence.
It’s not the most efficient approach, but it gets the job done and is quite intuitive. Note that we are running 20 iterations. Going beyond that number increases the run-time dramatically.
We shall now use the Thue-Morse sequence to generate the Koch curve. Here’s how we will use the sequence:
As you might have guessed, the code to implement the above algorithm is going to be very simple and straight-forward.
To draw the straight line, we’ll use the
lineTo() method of the context. And, to rotate the canvas, we’ll use the
rotate() method. Additionally, we’ll also use the
translate() method so that we always start the next line exactly where the previous line ended. Here’s the code:
If you open the page in a browser, you should be able to see the following graphic, which is a portion of the Koch curve:
Feel free to experiment with more iterations and different lengths for the line segments. However, you’ll see that the shape of the curve doesn’t really change much. That’s because it repeats itself infinitely, although it does converge to form something called a Koch Snowflake.