block by sxywu 9fc66f76d0217475f2e4

Art in Pi, Experiment #2

Full Screen

Inspired by @NadiehBremer‘s Exploring the Art hidden in Pi, implemented in canvas.

Built with blockbuilder.org

forked from sxywu‘s block: Art in Pi, Experiment #1

index.html

<!DOCTYPE html>
<head>
  <meta charset="utf-8">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
  <script src="//underscorejs.org/underscore-min.js"></script>
  <style>
    body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
    svg { width: 100%; height: 100%; }
  </style>
</head>

<body>
  <canvas id='canvas'></canvas>
  <script>
    var piString = "3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086513282306647093844609550582231725359408128481";
    var width = 800;
    var height = 800;
    var length = 50;
    // colors taken from visualcinnamon's original pi art post
    var colors = ['#F3C844', '#F1B34B', '#EC6959', '#DD406E', '#C24488',
                  '#A562A7', '#7B7EBF', '#4EA1B0', '#50BE8D', '#9ECA7D'];
    
    var canvas = document.getElementById('canvas');
    canvas.width = width;
    canvas.height = height;
    var ctx = canvas.getContext('2d');
    
    var x = width / 2;
    var y = height / 2;
    // draw pi
    _.each(piString, function(int) {
      int = parseInt(int);
      if (_.isNaN(int)) return;
      
      ctx.beginPath();
      ctx.moveTo(x, y);
      
      var radian = (2 * Math.PI) / 10 * int - (Math.PI / 2);
      x += length * Math.cos(radian);
      y += length * Math.sin(radian);

      ctx.strokeStyle = colors[int];
      ctx.lineWidth = 2;
      ctx.lineTo(x, y);
      ctx.stroke();
      ctx.closePath();
    });
    
    x = length * 2;
    y = length * 2;
    // draw legend
    _.each([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], function(int) {       
      var radian = (2 * Math.PI) / 10 * int - (Math.PI / 2);
      var x1 = 2 * Math.cos(radian) + x;
      var y1 = 2 * Math.sin(radian) + y;
      var x2 = length * Math.cos(radian) + x;
      var y2 = length * Math.sin(radian) + y;
      var textX = (length + 5) * Math.cos(radian) + x;
      var textY = (length + 5) * Math.sin(radian) + y;

      ctx.beginPath();
      ctx.moveTo(x1, y1);
      ctx.strokeStyle = colors[int];
      ctx.lineWidth = 2;
      ctx.lineTo(x2, y2);
      ctx.stroke();
      
      // all that making text look nice
      ctx.font = '12px Helvetica';
      ctx.fillStyle = '#666';
      if (int > 0 && int < 5) {
        ctx.textAlign = 'start';
      } else if (int > 5 && int < 10) {
        ctx.textAlign = 'end';
      } else {
        ctx.textAlign = 'center';
      }
      if (int > 2 && int < 8) {
        ctx.textBaseline = 'top';
      } else {
        ctx.textBaseline = 'bottom';
      }
      ctx.fillText(int, textX, textY); 
      ctx.closePath();
    });
    
		

  </script>
</body>