Categories
Computer English

Fractals in JavaScript Tutorial

In this tutorial I will demonstrate how to generate a simple tree and forest landscape. Using only JavaScript. This picture is not drawn using Paint. It is 100% generated by code.

fractals in javascript tutorial: How to make (program) fractals. This is a forest landscape. Copyright (c) Bruno Stroobandt. Infonosity.net.

How to program a fractal. Displayed on HTML page.

Fractals in Javascript Tutorial: In this tutorial I will demonstrate how to generate a simple tree and forest landscape. Using only JavaScript. This picture is not drawn using Paint. It is 100% generated by code.

What is a fractal?

It is an infinite repeating pattern. In this case it is a loop that draws a line. Then splits in two directions and draws two lines. BUT then each of this two new lines. Are lines themselves. So they each split into two new lines. And so on. (wiki fractal )

Of course this will freeze your computer since it is an infinite loop. That is why I limit the iteration by a factor of 9.

How to draw fractals in HTML using Javascript?

First we have to setup a canvas to draw on. This is done in the code below. Save that code as index.html (or index.htm)


    
        
        
        Fractal Test
        
    

You can even cut everything between and

Fractals in JavaScript (Tutorial)

So this was just the initialization of our html page. Below is the JavaScrip. We could put this also inside the html page. But I choose to put it in a separate file. If you want it in your html. Then cut the ‘scr=…’ and paste the code between the

It begins with setting the variables. And then you see the functions to draw lines. And trees. This is followed by drawing the background of our canvas in green and blue. (the sky and the grass 🙂 ) And then 2 loops that draw the road. And than last but not least it calls the tree drawing function 6 times. But each time on another position, creating the trees next to the road.



Back to English (index)

Back to Computer en Electronica (dutch index)