0

I am trying to create an Mandelbrot set in HTML5 canvas. But it is giving me noise surrounding the set. See the fiddle: https://jsfiddle.net/k1f9phw7/

I tried playing with every setting and tried to map brightness to the iteration count but with no success.

let pixelSize = 1;
let width = 500;
let height = 500;
let maxIterations = 400;
let mandelMin = -2.5;
let mandelMax = 2.5;
let infinity = 15;

function draw() {

let ctx = document.getElementById('canvas').getContext('2d');

for (var y = 0; y < height; y++) {

    for (var x = 0; x < width; x++) {

        var map = function (num, in_min, in_max, out_min, out_max) {
            return (num - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
        };

        var a = map(x, 0, width, mandelMin , mandelMax);
        var b = map(y, 0, width, mandelMin, mandelMax);

        var initialA = a;
        var initialB = b;

        var iterationCount = 0;

        while(iterationCount < maxIterations){

            //Echt
            var aa = (a * a) - (b * b);

            //Complex
            var bb = (2 * a * b);

            //De initiele waarde zijn c
            a = aa + initialA;
            b = bb + initialB;

            var result = Math.abs(a + b);

            //Is het oneindig?
            if( result >= infinity){
                break;
            }else{

                var brightness = 0;

                ctx.fillStyle = 'rgb('+ brightness +', '+ brightness +', '+ brightness +')';
                //Teken de pixel
                ctx.fillRect( map(a ,mandelMin, mandelMax, 0, width )  * pixelSize, map(b, mandelMin, mandelMax, 0, height) * pixelSize, pixelSize, pixelSize);
            }

            iterationCount++;

        }
    }
}
}
draw();
  • https://stackoverflow.com/questions/15399340/how-to-calculate-with-imaginary-numbers-in-javascript – Adam Jan 20 '19 at 16:35

1 Answers1

0

You are testing the function for an escaped value by summing a + b which is incorrect. It is more usual to test for a magnitude of 2.0 after which the function is known to eventually escape. This is simple to test with

a * a + b * b >= 4.0

especially as you need to square a and b anyway.

Weather Vane
  • 33,872
  • 7
  • 36
  • 56