DEV Community

Adrian
Adrian

Posted on

Coding challenge: Generate a Tree on your computer

Dear JavaScript programmer,

Imagine yourself being an artist... You have big dreams of drawing all sort of objects. But in order to prove your skills you first take the challenge and attempt to draw a tree.

When about to start you also remember... you’re also a coder! You don’t want to draw a tree with pen and paper but you want to draw it with code.

First you propose to take it easy and draw something symmetrical... but then you plan to tune the code to make the tree more realistic.

Alt Text
Alt Text
Alt Text

Your guide in this challenge are the above two images and the following stub HTML page.

The stub HTML page provides you with the canvas where the artist in you will express himself.

The stub code also provides you with a function: line – the only function, outside regular JavaScript constructs, you need to use to draw your trees.

<canvas id="canvas" width="800" height="600"></canvas>

<script>
    const canvas = document.getElementById('canvas');
    const ctx = canvas.getContext('2d');

    const line = (x1, y1, x2, y2) => {
        ctx.beginPath(); 
        ctx.moveTo(x1, y1);
        ctx.lineTo(x2, y2);
        ctx.stroke();        
    }

    // write here...

</script>
Enter fullscreen mode Exit fullscreen mode

Next level: If you feel adventurous, you can take this challenge to the next level: draw thicker trunk – thinner branches, draw trunk in brown – leaves in green, etc. (require individual research of canvas API).

Conclusion

I’m hoping that by working on this challenge you’ll have lots of fun. By solving it you’ll also get the chance to explore canvas drawing as well as some very important programming techniques.

Please post your solution as well as trees (images) in the thread.

Note

You can work on your challenge in any environment your prefer. If you want to quickly prototype the code you can use codeguppy.com canvas based environment. In codeguppy.com, line is already a predefined function (so you can skip the above stub).

Solution

First try to solve this challenge on your own and share the solution (as well as the generated trees) in the comments.

However, if you want to see the solution you can find it here.

Happy coding!

Top comments (0)