Creating 3D trees with some #CreativeJS

Random trees created using three.js and some creative JavaScript
Trees generated at random using some CreateiveJS and Three.js.

Over a month has passed since my last blog post and much has happened. We’ve had a wedding, a funeral at sea (maybe in bad taste!) and I’ve gone full-time freelance (yay!). I’ve had a little more time to work on a couple of personal projects so I’ve finished one that I started way back in January.

I had the pleasure of attending a Creative JavaScript course in Brighton, UK, hosted by Seb Lee-Delisle; a two-day course that covered a wealth of topics from Vanilla JavaScript to Three.js. If you’re looking for some inspiration I highly recommend looking out for one of Seb’s courses. Great fun and you get to meet some really nice people. Quick tip: You may want to brush up on a little Trigonometry before you go as it’s used numerous times. I knew that A-Level Mathematics course would come in useful one day :).

Seb produced a demo in Canvas that created ‘trees’ and it really caught my eye. The trees were in 2D so as I’ve had a bit of experience with Three.js I decided to create a 3D version! I’m quite happy with the result although I’ve had to restrict the number of branches rendered due to the lack of dedicated graphics card in my laptop; I get about 1fps when stopping at a branch length value of 10 (line 211) :(

The demo also allowed me to use the new request animation frame API which vendors have added to aid animations in browsers. The main advantage of using it is if you have the animation running in a tab that isn’t visible, the browser will know to stop the animation! Using the old setTimeout method, the animation still runs in the background and uses up precious CPU, memory and battery power (especially on a laptop). As with most new browser features the API isn’t set in stone (yet) but luckily Paul Irish has created a polyfill that falls back to setTimeout in older browsers.

View the demo here; reload for different trees. JavaScript finally seems to be coming of age!

Update: Original credit goes to Jean-No with his amazing OpenProcessing work! I’ll be bookmarking that link, some stunning work there. Thanks to Seb for pointing out who to credit :)