# fractal tree
This fractal tree is built entirely with the Graphery SVG library, and it is animated with the sequence
plugin.
edit in codepen.io (opens new window)
We will now explain step by step how to create a dynamic SVG of this type.
# Imports
The first step, if we haven't already done so, is to load the Graphery SVG library, Helpers plugin and Sequence Plugin.
In our case, we have chosen to include the code within a script type=module
and we will use the import
expression.
The plugins must be applied with gySVG.extend()
.
see: load gySVG | Sequence Plugin
# Create the SVG
To create the graph we are going to use gySVG()
and we are going to configure the viewBox.
const svg = gySVG().viewBox(0, 0, 600, 600).width(400).height(400);
svg.attachTo('#example-fractal-tree');
# Create the Sequence object
For build the animations, we will use the Sequence object created with svg.Seq()
:
const seq = svg.Seq();
# Create the tree
We have written a function to create the fractal tree, this function creates a branch and divides it into two more branches with 16 degrees and 20% less length.
(function drawBranch (startX = 300, startY = 600, len = 120, angle = 0, remain = 10, delay = 0) {
const {x: endX, y: endY} = gySVG.polar2cartesian(startX, startY, len, angle);
const duration = 600;
const element = svg.add('line')
.x1(startX).y1(startY).x2(startX).y2(startY)
.stroke('#45ae13ff').stroke_width(remain);
seq.add(element, {x2: endX, y2: endY}, {delay, duration});
if (remain) {
drawBranch(endX, endY, len * 0.8, angle - 16, remain - 1, delay + duration);
drawBranch(endX, endY, len * 0.8, angle + 16, remain - 1, delay + duration);
}
})();
seq.play();
We had used seq.add()
for include the animation and run the animation sequence with seq.play()
.
# The complete code
If we put all these steps together this is the example's code:
import gySVG from 'https://cdn.graphery.online/svg/1.0.0/module/index.js';
import helpers from "https://cdn.graphery.online/svg/1.0.0/module/helpers.plugin.js";
import sequence from "https://cdn.graphery.online/svg/1.0.0/module/sequence.plugin.js";
gySVG.extend(helpers);
gySVG.extend(sequence);
const svg = gySVG().viewBox(0, 0, 600, 600).width(400).height(400);
svg.attachTo('#example-fractal-tree');
const seq = svg.Seq();
(function drawBranch (startX = 300, startY = 600, len = 120, angle = 0, remain = 10, delay = 0) {
const duration = 600;
const {x: endX, y: endY} = gySVG.polar2cartesian(startX, startY, len, angle);
const element = svg.add('line')
.x1(startX).y1(startY).x2(startX).y2(startY)
.stroke('#45ae13ff').stroke_width(remain);
seq.add(element, {x2: endX, y2: endY}, {delay, duration});
if (remain) {
drawBranch(endX, endY, len * 0.8, angle - 16, remain - 1, delay + duration);
drawBranch(endX, endY, len * 0.8, angle + 16, remain - 1, delay + duration);
}
})();
seq.play();
← car racing countdown →