|
| 1 | +function drawPixel(ctx, x, y, color) { |
| 2 | + var g = 255 - color * 255; |
| 3 | + g = g|0; |
| 4 | + ctx.beginPath(); |
| 5 | + ctx.strokeStyle = 'rgb(' + g + ',' + g + ',' + g + ')'; |
| 6 | + ctx.moveTo(x + 0.5, y); |
| 7 | + ctx.lineTo(x + 0.5, y + 1); |
| 8 | + ctx.stroke(); |
| 9 | +} |
| 10 | + |
| 11 | +function Fractal(canvas) { |
| 12 | + this.canvas_ = canvas; |
| 13 | + this.ctx_ = canvas.getContext('2d'); |
| 14 | + |
| 15 | + this.re_min_ = -2; |
| 16 | + this.re_max_ = 2; |
| 17 | + this.im_min_ = -2; |
| 18 | + this.im_max_ = 2; |
| 19 | + |
| 20 | + this.iters_ = 100; |
| 21 | + |
| 22 | + this.draw = function() { |
| 23 | + console.log('starting to draw'); |
| 24 | + for (var y = 0; y < this.canvas_.height; y++) { |
| 25 | + window.setTimeout(function(y) { |
| 26 | + for (var x = 0; x < this.canvas_.width; x++) { |
| 27 | + // map the canvas's (x,y) to a point a+bi on the complex plane. |
| 28 | + var a = x / this.canvas_.width * (this.re_max_ - this.re_min_) + this.re_min_; |
| 29 | + var b = (1 - y / this.canvas_.height) * (this.im_max_ - this.im_min_) + this.im_min_; |
| 30 | + drawPixel(this.ctx_, x, y, this.fn_(a, b)); |
| 31 | + } |
| 32 | + }.bind(this, y), 0); |
| 33 | + } |
| 34 | + console.log('done drawing'); |
| 35 | + }; |
| 36 | + |
| 37 | + // The function to draw a point in the set. Takes a point a+bi on the complex |
| 38 | + // plane and returns a value between 0 and 1 for the shade to draw - 0 for |
| 39 | + // not in the set, and 1 for in the set. |
| 40 | + this.fn_ = function(a, b) { |
| 41 | + var z_re = 0; |
| 42 | + var z_im = 0; |
| 43 | + for (var i = 0; i < this.iters_; i++) { |
| 44 | + // compute z = z^2 + a+bi: |
| 45 | + // z = (z_re + z_im*i)^2 + a + b*i |
| 46 | + // z = z_re^2 + 2*z_re*z_im*i - z_im^2 + a + b*i |
| 47 | + // z = z_re^2 - z_im^2 + a + i*(2*z_re*z_im + b) |
| 48 | + var re = z_re*z_re - z_im*z_im + a; |
| 49 | + z_im = 2*z_re*z_im + b; |
| 50 | + z_re = re; |
| 51 | + // if (z_re > 2 || z_re < -2 || z_im > 2 || z_im < -2) { |
| 52 | + if (Math.sqrt(z_re*z_re + z_im*z_im) > 2) { |
| 53 | + return i / this.iters_; |
| 54 | + } |
| 55 | + } |
| 56 | + return 1; |
| 57 | + }; |
| 58 | +}; |
| 59 | + |
| 60 | +window.addEventListener('load', function() { |
| 61 | + var canvas = document.getElementById('mandelbrot'); |
| 62 | + canvas.width = window.innerWidth; |
| 63 | + canvas.height = window.innerHeight; |
| 64 | + var fractal = new Fractal(canvas); |
| 65 | + fractal.draw(); |
| 66 | + |
| 67 | + window.addEventListener('resize', function() { |
| 68 | + canvas.width = window.innerWidth; |
| 69 | + canvas.height = window.innerHeight; |
| 70 | + fractal.draw(); |
| 71 | + }); |
| 72 | +}); |
0 commit comments