Home > Article > Web Front-end > p5.js implements Pythagoras tree (with code)
This time I will bring you p5.js to implement the Pythagoras tree (with code), and p5.js to implement the Pythagoras tree. What are the precautions?. Here are the actual cases. , let’s take a look.
The effect is as follows:
Main method
translate()
rotate()
rect()
push()
pop()
map()
##Main idea
RecursionSketch
Process Breakdown
1. Recursive function of Pythagoras tree
function Pythagorian(x){ noStroke(); fill(107, 142, 35,map(x, 0, a, 150, 255));//根据正方形边长设置填充色 rect(0,0,x,x);//绘制当前的正方形 if(x <= 3) return 0;//当正方形边长小于3时,结束递归 /* 绘制右上角的正方形 */ push(); rotate(PI / 2 - t);//坐标轴顺时针旋转约37deg translate(0,-x/5 * 3 - x/5*4);//坐标轴向上平移3边+4边的长度 Pythagorian(x/5*4);//递归调用毕达哥拉斯函数 pop(); /* 绘制左上角的正方形 */ push(); rotate( - t);//坐标轴逆时针旋转约53deg translate(0,-x/5 * 3);//坐标轴向上平移3边的长度 Pythagorian(x/5*3);//递归调用毕达哥拉斯函数 pop(); }
2. Declare variables and create canvas
var a = 100; //最大正方形边长 var t;//4边所对应的角度 function setup(){ t = 53.1301024 / 360 * 2 * PI;//约为53deg createCanvas(windowWidth, windowHeight);//创建画布 background(255); noLoop();//draw()函数只执行一次 }
3. Start drawing the Pythagoras tree
function draw(){ translate(windowWidth/2, windowHeight - a * 2);//将坐标系平移至画布中间底部 Pythagorian(a);//调用毕达哥拉斯递归函数 }Complete code for drawing the Pythagoras tree
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(); }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:
JS uses regular expressions to determine date of birth
How does JS store original values and reference values
The above is the detailed content of p5.js implements Pythagoras tree (with code). For more information, please follow other related articles on the PHP Chinese website!