謝爾賓斯基三角墊


使用混沌描點的方法畫出來的,很神奇。以下是網頁代碼,只能在支持html5的瀏覽器上看。

<html>
  <canvas id="blackboard" width="1000" height="1000">
  </canvas>
  <script>
    function draw()
    {
      // 獲取畫布
      var canv = document.getElementById("blackboard");
      var context = canv.getContext("2d");
      
      // 獲得像素數組
      var bitArray = context.getImageData(0, 0, 1000, 1000);

      // unit是二分之一的邊長
      var unit = 500;

      // 隨便定義一個初始點
      var startPointX = 550;
      var startPointY = 800;

      for(var i=0; i< 100000; i++)
      {
        // 生成一個隨機數
        var sNum = Math.floor(Math.random()*3);

        // 定義要畫的點
        var tempPointX;
        var tempPointY;

        // A點座標是(unit, 0)
        if(sNum == 0)
        {
          tempPointX = Math.round(unit + (startPointX-unit)/2);
          tempPointY = Math.round(0 + (startPointY-0)/2);
        }
        // B點座標是(2*unit, 根號3*unit)
        else if(sNum == 1)
        {
          tempPointX = Math.round(2*unit + (startPointX-2*unit)/2);
          tempPointY = Math.round(Math.sqrt(3)*unit + (startPointY-Math.sqrt(3)*unit)/2);
        }
        // C點座標是(0, 根號3*unit)
        else if(sNum == 2)
        {
          tempPointX = Math.round(0 + (startPointX-0)/2);
          tempPointY = Math.round(Math.sqrt(3)*unit + (startPointY-Math.sqrt(3)*unit)/2);
        }

        // 在這個座標上畫藍色點
        bitArray.data[(1000*tempPointY + tempPointX)*4] = 0;
        bitArray.data[(1000*tempPointY + tempPointX)*4+1] = 0;
        bitArray.data[(1000*tempPointY + tempPointX)*4+2] = 255;
        bitArray.data[(1000*tempPointY + tempPointX)*4+3] = 255;

        // 迭代
        startPointX = tempPointX;
        startPointY = tempPointY;
      }
 
      // 提交到畫布
      context.putImageData(bitArray, 0, 0);
    }

    window.addEventListener("load", draw, true);
  </script>
</html>


發佈了56 篇原創文章 · 獲贊 7 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章