Public
Edited
Oct 1, 2023
1 star
Insert cell
Insert cell
{
const color_fn = (x, y) => {
const value = maldelbrot_pixel(x / WIDTH, y / HEIGHT);
return value == 0 ? '#000' : `hsl(0, 100%, ${100 - value}%)`;
};
return draw_board(color_fn);
}
Insert cell
{
const color_fn = (x, y) => {
const value = maldelbrot_pixel(x / WIDTH, y / HEIGHT);
return value == 0 ? '#000' : '#fff';
};
return draw_board(color_fn);
}
Insert cell
Insert cell
function maldelbrot_pixel(x, y) {
const max_iterations = 100;
const escape_radius = 40;
let x1 = 0;
let y1 = 0;
let w = 0;
const x0 = scale_x(x);
const y0 = scale_y(y);

for (let n = 0; n < max_iterations; n++) {
const x2 = x1 - y1 + x0
const y2 = w - x1 - y1 + y0
x1 = x2 * x2
y1 = y2 * y2
w = (x2 + y2) * (x2 + y2)

if (x1 + y1 > escape_radius) {
return (n * 1.0 / max_iterations) * 100; // Return percentage of maxIterations
}
}

return 0; // 0 indicates in the set
}
Insert cell
Insert cell
WIDTH = 500
Insert cell
HEIGHT = 500
Insert cell
function make_svg() {
const area = d3.create('div');
const header = area.append('div');
const svg = area.append('svg')
.attr('width', WIDTH)
.attr('height', HEIGHT);
return [area, svg];
}
Insert cell
function draw_board(color_fn) {
const [area, svg] = make_svg();
for (let i = 0; i < HEIGHT; i++) {
for (let j = 0; j < WIDTH; j++) {
const color = color_fn(j, i);
draw_pixel(svg, j, i, color);
}
}
return area.node();
}
Insert cell
function draw_pixel(svg, x, y, color) {
svg.append("rect")
.attr("x", x)
.attr("y", y)
.attr("width", 1)
.attr("height", 1)
.attr("fill", color);
}
Insert cell
function scale_x(x) {
return scale(x, -2.00, 0.60);
}
Insert cell
function scale_y(y) {
return scale(y, -1.12, 1.12);
}
Insert cell
// Scales a [0, 1] into the interval [a, b]
function scale(v, a, b) {
return v * (b - a) + a;
}
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more