0

I'm trying to create the Mandelbrot set and other Julia Sets in JavaScript for a school project. I've looked over my code and it looks like it follows the formula correctly, but my Mandelbrot set is not being drawn correctly. Any tips on what's wrong?

<!DOCTYPE html>
<html>
   <head>
   </head>
   <body>
      <canvas id="canvas" width="600" height="600" style="background-color: black;"></canvas>
      <script>
          //center the canvas at the coordinate plane
          var canvas = document.getElementById("canvas");
          const width = canvas.width;
          const height = canvas.height;
          const scalingFactor = width / 4;
          var graphics = canvas.getContext("2d");

          function mandelbrotDraw(iterations) {
               //multiply by 4 in order to get the scaling right
               for (var i = 0; i <= width; i++) {
                   for (var j = 0; j <= height; j++) {
                       var x = 0;
                       var y = 0;

                       var re = (i - width / 2) / scalingFactor;
                       var im = (j - height / 2) / scalingFactor;

                       var k = 0;

                       while (x * x + y * y <= 4 && k < iterations) {
                           x = x * x - y * y + re;
                           y = 2 * x * y + im;

                           k++;
                       }

                       if (k < iterations) {
                           graphics.fillStyle = "black";
                           graphics.fillRect(i, j, 1, 1);
                       } else {
                           graphics.fillStyle = "white";
                           graphics.fillRect(i, j, 1, 1);
                       }
                   }
               }
           }

           mandelbrotDraw(25);
      </script>
   </body>
</html>
  • 1
    When you update `y`, you need to use the old value of `x`, not the new one. – Mark Dickinson May 08 '22 at 06:36
  • There are a good few duplicates. See for example https://stackoverflow.com/q/56299653/270986 – Mark Dickinson May 08 '22 at 06:43
  • Thank you for your help I was looking for a solution for the longest time but I just couldn't seem to figure it out. – Magyarorszag May 08 '22 at 15:34
  • see these: [Can't find a way to color the Mandelbrot-set the way i'm aiming for](https://stackoverflow.com/a/56197067/2521214) and [What are the fastest algorithms for rendering the mandelbrot set?](https://stackoverflow.com/a/66719738/2521214) for inspiration and if its not enough see also: [How to express tetration function, for complex numbers](https://stackoverflow.com/a/56735614/2521214) – Spektre May 09 '22 at 08:01

0 Answers0