JavaScript graphic example: random Sierpinski triangle


      stayJavaScript graphic example: Sierpinski triangleIn this paper, we introduce the basic drawing method of Sierpinski triangleJavaScript graphics example: iterated function system generated graphicsIn this paper, the method of generating Sierpinski triangle by IFS is introduced. Next, we introduce two construction methods of Sierpinski triangle to expand the knowledge.

1. Random point method

Sierpinski triangle can be obtained by using the method of random points. The specific process is as follows:

(1) Arbitrarily take three points a, B and C on the plane to form a triangle, and arbitrarily take a point P in the triangle ABC;

(2) Calculate the midpoint P1 of any vertex of P and a, B, C;

(3) Draw the midpoint P1;

(4) Take P1 as a new P point and turn to step (2) until the number of points traced reaches the specified requirements (such as 10000 points).

According to the above idea, the following HTML file is compiled. In programming, for the sake of simplicity, it is not guaranteed that the initial point P must be in the triangle ABC (there may be several scattered points outside the triangle, but the final result will not be affected), and it is not judged that the three points a, B and C may be collinear (the triangle cannot be formed at this time). Interested readers can deal with these two situations to improve the code.

Random Sierpinski triangle

     var canvas=document.getElementById(‘myCanvas’);

     var ctx=canvas.getContext(‘2d’);

     function draw()






         var ax=Math.floor(Math.random()*200+50);

         var ay=Math.floor(Math.random()*200+50);

         var bx=Math.floor(Math.random()*200+50);

         var by=Math.floor(Math.random()*200+50);

         var cx=Math.floor(Math.random()*200+50);

         var cy=Math.floor(Math.random()*200+50);

         var px=Math.floor(Math.random()*200+50);

         var py=Math.floor(Math.random()*200+50);

         var dx=0;

         var dy=0;

         for (i=0; i<10000; i++)


             index =Math.floor(Math.random()*3+1);

             if (index==1)


                dx = (ax + px)/2;

                dy = (ay + py)/2;


             else if (index == 2)


                dx = (bx + px)/2;

                dy = (by + py)/2;




               dx = (cx + px)/2;

               dy = (cy + py)/2;



            px = dx;

            py = dy;