本文介绍了p5.js 毕达哥拉斯树的实现代码,分享给大家,具体如下:
效果如下:
主要方法@H_502_9@
- translate()
- rotate()
- rect()
- push()
- pop()
- map()
主要思想@H_502_9@
递归
草图@H_502_9@
过程分解@H_502_9@
一、毕达哥拉斯树的递归函数@H_502_9@
if(x <= 3) return 0;//当正方形边长小于3时,结束递归
/ 绘制右上角的正方形 /
push();
rotate(PI / 2 - t);//坐标轴顺时针旋转约37deg
translate(0,-x/5 3 - x/54);//坐标轴向上平移3边+4边的长度
Pythagorian(x/5*4);//递归调用毕达哥拉斯函数
pop();
/ 绘制左上角的正方形 /
push();
rotate( - t);//坐标轴逆时针旋转约53deg
translate(0,-x/5 3);//坐标轴向上平移3边的长度
Pythagorian(x/53);//递归调用毕达哥拉斯函数
pop();
}
/ 绘制右上角的正方形 /
push();
rotate(PI / 2 - t);//坐标轴顺时针旋转约37deg
translate(0,-x/5 3 - x/54);//坐标轴向上平移3边+4边的长度
Pythagorian(x/5*4);//递归调用毕达哥拉斯函数
pop();
/ 绘制左上角的正方形 /
push();
rotate( - t);//坐标轴逆时针旋转约53deg
translate(0,-x/5 3);//坐标轴向上平移3边的长度
Pythagorian(x/53);//递归调用毕达哥拉斯函数
pop();
}
二、声明变量、创建画布@H_502_9@
301024 / 360 * 2 * PI;//约为53deg
createCanvas(windowWidth,windowHeight);//创建画布
background(255);
noLoop();//draw()函数只执行一次
}
三、开始绘制毕达哥拉斯树@H_502_9@
绘制毕达哥拉斯树完整代码
301024 / 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,255));
rect(0,x);
if(x <= 3) return 0;
push();
rotate(PI / 2 - t);
translate(0,-x/5 3 - x/54);
Pythagorian(x/5*4);
pop();
push();
rotate( - t);
translate(0,-x/5 3);
Pythagorian(x/53);
pop();
}