Canvas Mandelbrot

Canvas is not supported on this browser.

Source Code

<script type="text/javascript">
  //<![CDATA[

  // algorithm was copied from this site:
  // http://rosettacode.org/wiki/Mandelbrot_set#JavaScript

  function mandelbrotIteration(cx, cy, max) {
      var i;
      var x = 0.0;
      var y = 0.0;
      for (var i = 0; i < max && x * x + y * y <= 4; i++) {
          var tmp = 2 * x * y;
          x = x * x - y * y + cx;
          y = tmp + cy;
      }
      return i;
  }

  // draw mandelbrot on canvas
  var drawMandelbrot = function() {
      var canvas = document.getElementById('canvasMandelbrot');
      if (canvas.getContext) {
          var ctx = canvas.getContext('2d');

          // set canvas size (to maximum for window size)
          var width = window.innerWidth - ctx.canvas.offsetLeft - 20;
          var height = window.innerHeight - ctx.canvas.offsetTop - 20;
          ctx.canvas.width = width;
          ctx.canvas.height = height;

          var xmin = -2.0;
          var xmax = 1.0;
          var ymin = -1.0;
          var ymax = 1.0;
          var iterations = 1000;
          var img = ctx.getImageData(0, 0, width, height);
          var pix = img.data;
          for (var ix = 0; ix < width; ++ix) {
              for (var iy = 0; iy < height; ++iy) {
                  var x = xmin + (xmax - xmin) * ix / (width - 1);
                  var y = ymin + (ymax - ymin) * iy / (height - 1);
                  var i = mandelbrotIteration(x, y, iterations);
                  var ppos = 4 * (width * iy + ix);
                  if (i == iterations) {
                      pix[ppos] = 0;
                      pix[ppos + 1] = 0;
                      pix[ppos + 2] = 0;
                  } else {
                      var c = 3 * Math.log(i) / Math.log(iterations - 1.0);
                      if (c < 1) {
                          pix[ppos] = 255 * c;
                          pix[ppos + 1] = 0;
                          pix[ppos + 2] = 0;
                      } else if (c < 2) {
                          pix[ppos] = 255;
                          pix[ppos + 1] = 255 * (c - 1);
                          pix[ppos + 2] = 0;
                      } else {
                          pix[ppos] = 255;
                          pix[ppos + 1] = 255;
                          pix[ppos + 2] = 255 * (c - 2);
                      }
                  }
                  pix[ppos + 3] = 255;
              }
              ctx.putImageData(img, 0, 0);
          }
      }
  }

  window.onload = drawMandelbrot;

  //]]>
</script>

<h1>Canvas Mandelbrot</h1>

<canvas id="canvasMandelbrot" width="200" height="200">
  <p>Canvas is not supported on this browser.</p>
</canvas>