And yet it moves

And yet it moves

Remember the fractal tree from earlier? Now that you know how to render updates, I have a new exercise for you. Your task is to bring the tree to life!

In the editor below, I’ve provided you with a FractalTree component. The available props are documented on the propTypes object in FractalTree.js, but there are two props in particular that you may find interesting:

  • lean

    A number that specifies how far the tree leans to one side or the other. I like numbers between -0.15 and 0.15.

  • sprout

    A number that specifies how much the tree should sprout upwards. I like numbers between 0.3 and 0.5.

main.js
FractalTree.js
getFractalStyle.js
index.html
New
Build In Progress

To make the tree sway, all you need to do is repeatedly render the tree while cycling the values of lean and sprout between two numbers.

To schedule each render, you can use window.setTimeout() or window.requestAnimationFrame() – whatever you feel most comfortable with. With each rendered frame, you can use the result of Date.now() to calcaulate the number of milliseconds that have passed since the previous frame.

You could also use window.setInterval(), but this can cause problems when frames take longer to render than the specified interval. And given how heavy the tree can be, there’s a good chance of this happening.

If you need some help with picking the values of lean and sprout, see the section below. If you get stuck, feel free to check my solution – as long as you’ve given it your best try before you do.

And once you’re happy with your tree, you can move on to the next lesson!

Cycling numbers between two values

You can skip this section if you already know how to use Math.sin(time) to cycle between two numbers.

To make the tree sway, you’ll need to cycle the lean prop between roughly -0.5 and 0.5 as time passes. But how do you turn an ever-increasing number like time into a cycling number? With trigonometry functions, of course! And in particular, with Math.sin().

Seeing is believing, so here’s an example that uses a Scope component to show how the value of Math.sin(time) changes over time.

main.js
Scope.js
index.html
New
Build In Progress
Mark as completed and progress to next section.