谢尔宾斯基三角垫


使用混沌描点的方法画出来的,很神奇。以下是网页代码,只能在支持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万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章