This time I will show you how to implement the Pythagoras tree using JS. What are the things to note when implementing the Pythagoras tree using JS? The following is a practical case. Let’s take a look. . The effect is as follows:

Main method
translate()-
rotate() rect() push() pop() map() ##Main idea
Recursion
Sketch

Process Breakdown
1.
Recursive function of Pythagoras tree
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <strong><a href= "https://www.php.cn/code/9697.html" target= "_blank" > function Pythagorian(x){
noStroke();
fill(107, 142, 35,map(x, 0, a, 150, 255));
rect(0,0,x,x);
if (x <= 3) return 0;
push();
rotate(PI / 2 - t);
translate(0,-x/5 * 3 - x/5*4);
Pythagorian(x/5*4);
pop();
push();
rotate( - t);
translate(0,-x/5 * 3);
Pythagorian(x/5*3);
pop();
}</a></strong>
|
2. Declare variables and create canvas
1 2 3 4 5 6 7 8 | var a = 100;
var t;
function setup(){
t = 53.1301024 / 360 * 2 * PI;
createCanvas(windowWidth, windowHeight);
background(255);
noLoop();
}
|
Copy after login
3. Start drawing the Pythagoras tree
1 2 3 4 | function draw(){
translate(windowWidth/2, windowHeight - a * 2);
Pythagorian(a);
}
|
Copy after login
Complete code for drawing the Pythagoras tree1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | var a = 100;
var t;
function setup(){
t = 53.1301024 / 360 * 2 * PI;
createCanvas(windowWidth, windowHeight);
background(255);
noLoop();
}
function draw(){
translate(windowWidth/2, windowHeight - a * 2);
Pythagorian(a);
}
function Pythagorian(x){
noStroke();
fill(107, 142, 35,map(x, 0, a, 150, 255));
rect(0,0,x,x);
if (x <= 3) return 0;
push();
rotate(PI / 2 - t);
translate(0,-x/5 * 3 - x/5*4);
Pythagorian(x/5*4);
pop();
push();
rotate( - t);
translate(0,-x/5 * 3);
Pythagorian(x/5*3);
pop();
}
|
Copy after login
I believe you have mastered the method after reading the case in this article, and there will be more exciting things Please pay attention to other related articles on php Chinese website!
Recommended reading:
What are the storage methods of JS original values and reference values
How Vue formats filters
Detailed explanation of the steps to use third-party UI frameworks and controls in Angular
The above is the detailed content of How to implement Pythagoras tree using JS. For more information, please follow other related articles on the PHP Chinese website!