Дерево Пифагора

Материал из Department of Theoretical and Applied Mechanics
Перейти к: навигация, поиск

Описание

Алгоритм построения дерева Пифагора с выбором углов и глубиной прорисовки. Файл:

Особенности

В классическом дереве Пифагора угол равен 45 градусам, также можно построить обобщённое дерево Пифагора при использовании других углов.

Визуализация

Код программы

Код программы на языке JavaScript:

<syntaxhighlight lang="javascript" line start="1" enclose="div"> } window.addEventListener("load", program_code, false); function program_code() {

var ctx = canvas_example.getContext('2d'); var w = canvas_example.width; var h = canvas_example.height;

//var n_max= input1.value;

//ctx.strokeRect(w/2, h/2, 100,100); //ctx.translate(w/2 + 50, h/2 +50); function draw_square(x, y, r,R){ ctx.fillStyle= 'rgb('+Math.floor(255-R)+', 165, 150)'; ctx.fillRect(x,y,r,r); } function Pyth_fract(a,n){ var n_max= input1.value; var alpha= Math.PI*(input2.value)/180; if (n_max < 1) console.log("n must be >= 1") if (n > n_max) return; var b = Math.round( a*Math.cos(alpha) ); var c = Math.round( a*Math.sin(alpha) ); ctx.translate ( -Math.round((b/2+c/2)*Math.sin(alpha)),Math.round (-a/2 - (b/2+c/2)*Math.cos(alpha) )); ctx.rotate( -alpha); draw_square(-b/2, -b/2, b, c); Pyth_fract(b,n+1 ) ; ctx.rotate(alpha); ctx.translate ( Math.round((b/2 + c/2)*Math.sin(alpha)),-Math.round (-a/2 - (b/2+c/2)*Math.cos(alpha) )); ctx.translate ( +Math.round((c/2 + b/2)*Math.cos(alpha)), Math.round (-a/2 -(c/2+b/2)*Math.sin(alpha) )); ctx.rotate(Math.PI/2-alpha) ;

   draw_square(-c/2, -c/2, c, c);
    Pyth_fract(c, n+1 ) ;

ctx.rotate(-Math.PI/2+alpha); ctx.translate ( -Math.round((c/2 + b/2)*Math.cos(alpha)), -Math.round (-a/2 -(c/2+b/2)*Math.sin(alpha) )); } function DrawP(){ draw_square(w/2, h/2, 50, 50); ctx.translate(w/2 + 25, h/2 +25); Pyth_fract(50, 1); } draw.onclick=function(){ ctx.clearRect(0,0,w,h); DrawP() ctx.translate(-w/2 - 25, -h/2-25 ); } //Pyth_fract(100, 1, Math.PI*1/4);

}