本文介紹了p5.js 畢達哥拉斯樹的實現代碼,分享給大家,具體如下:
效果如下:
主要方法
主要思想
遞歸
草圖
過程分解
一、畢達哥拉斯樹的遞歸函數
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(); }
二、聲明變量、創建畫布
var a = 100; //最大正方形邊長 var t;//4邊所對應的角度 function setup(){ t = 53.1301024 / 360 * 2 * PI;//約為53deg createCanvas(windowWidth, windowHeight);//創建畫布 background(255); noLoop();//draw()函數只執行一次 }
三、開始繪制畢達哥拉斯樹
function draw(){ translate(windowWidth/2, windowHeight - a * 2);//將坐標系平移至畫布中間底部 Pythagorian(a);//調用畢達哥拉斯遞歸函數 }
繪制畢達哥拉斯樹完整代碼
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(); }
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com