Tutorial: fractals with only 25 lines of code

The famous Mandelbrot set:

Can you give it a color gradient, so that it looks better?

Like this?


Or like this?

2 Likes

Adding one more line, and modifying two others, for a grand total of 26 lines, gives us some pretty colors.

var mapping = [[66, 30, 15], [25, 7, 26], [9, 1, 47], [4, 4, 73], [0, 7, 100], [12, 44, 138], [24, 82, 177], [57, 125, 209], [134, 181, 229], [211, 236, 248], [241, 233, 191], [248, 201, 95], [255, 170, 0], [204, 128, 0], [153, 87, 0], [106, 52, 3]];
...
color = (i < 255) ? mapping[i % mapping.length] : [0, 0, 0];
...
context.fillStyle = "rgb(" + color.join(",") + ")";

Giving us images that look like this:

You can change the mapping to any RGB colors that you want, making the array as large as you want too!

3 Likes

For reference, the colors being used are:

And of course, black for when the i variable escapes out as far as 255.

Very interesting.

I notice that using 'use strict' complains about zx and zy, meh.

Now to see if I can get it to generate random colors.
(writing code for fun almost always wins out over doing chores :wink: )

1 Like

only because someone left them out of the var at the top of the code.

2 Likes

That was fun. A quick change from a hard coded mapping array.

function return_random() {
  return Math.floor(Math.random() * 255) + 0;  
}
var mapping = [];
for (var i = 0; i < 16; i++) {
  var temp_arr = [];
  var red_val = return_random();
  var green_val = return_random();
  var blue_val = return_random();
  temp_arr.push(red_val, green_val, blue_val);
  mapping.push(temp_arr);
}
2 Likes

Woah! Like, psychedelic man!

5 Likes

Welcome to the forums, @js_fan.

Is this your own tutorial, or one you found and wanted to share? (Either way, it seems to be providing hours of entertainment!)

1 Like

Brilliant comments, guys! I’m impressed!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.