Mandelbrot mit JSXGraph
Aus Wiki1
(Unterschied zwischen Versionen)
Zeile 9: | Zeile 9: | ||
// Slider für Iterationstiefe | // Slider für Iterationstiefe | ||
- | const slider = board.create('slider', [[-2.3, 1.3], [1, 1.3], [10, | + | const slider = board.create('slider', [[-2.3, 1.3], [1, 1.3], [10, 50, 300]], { |
name:'Tiefe', | name:'Tiefe', | ||
snapWidth:1 | snapWidth:1 | ||
}); | }); | ||
- | // | + | // Canvas ins DOM hängen |
+ | const div = document.getElementById('jxgbox'); | ||
+ | const canvas = document.createElement('canvas'); | ||
+ | canvas.width = 800; | ||
+ | canvas.height = 600; | ||
+ | canvas.style.position = 'absolute'; | ||
+ | canvas.style.left = "0px"; | ||
+ | canvas.style.top = "0px"; | ||
+ | div.appendChild(canvas); | ||
+ | const ctx = canvas.getContext('2d'); | ||
+ | |||
function mandelbrotIter(cx, cy, maxIter) { | function mandelbrotIter(cx, cy, maxIter) { | ||
- | let x = 0, y = 0 | + | let x = 0, y = 0, iter = 0; |
- | + | ||
while (x*x + y*y <= 4 && iter < maxIter) { | while (x*x + y*y <= 4 && iter < maxIter) { | ||
- | + | const xtemp = x*x - y*y + cx; | |
y = 2*x*y + cy; | y = 2*x*y + cy; | ||
x = xtemp; | x = xtemp; | ||
Zeile 27: | Zeile 36: | ||
} | } | ||
- | + | function drawMandelbrot(maxIter) { | |
- | + | const bb = board.getBoundingBox(); // [x_min, y_max, x_max, y_min] | |
- | + | const img = ctx.createImageData(canvas.width, canvas.height); | |
- | + | ||
- | + | for (let px = 0; px < canvas.width; px++) { | |
+ | for (let py = 0; py < canvas.height; py++) { | ||
+ | // Koordinaten im Mandelbrot-Bereich | ||
+ | const cx = bb[0] + (px / canvas.width) * (bb[2] - bb[0]); | ||
+ | const cy = bb[3] + (py / canvas.height) * (bb[1] - bb[3]); | ||
- | + | const iter = mandelbrotIter(cx, cy, maxIter); | |
- | + | const idx = 4 * (py * canvas.width + px); | |
- | + | ||
- | + | ||
- | + | if (iter >= maxIter) { | |
- | + | img.data[idx] = 0; // R | |
- | + | img.data[idx+1] = 0; // G | |
- | + | img.data[idx+2] = 0; // B | |
- | + | img.data[idx+3] = 255; // A | |
- | + | } else { | |
- | + | const c = Math.floor(255 * iter / maxIter); | |
- | + | img.data[idx] = c; // R | |
- | + | img.data[idx+1] = 100; // G | |
- | + | img.data[idx+2] = 255 - c; // B | |
- | + | img.data[idx+3] = 255; // A | |
- | + | } | |
- | + | } | |
- | + | ||
- | + | ||
} | } | ||
+ | ctx.putImageData(img, 0, 0); | ||
} | } | ||
- | // | + | // Erneuern, wenn Slider bewegt wird |
- | + | slider.on('drag', () => { | |
- | + | drawMandelbrot(Math.round(slider.Value())); | |
- | + | ||
- | + | ||
- | + | ||
- | + | ||
- | + | ||
- | + | ||
- | + | ||
- | + | ||
- | + | ||
- | + | ||
}); | }); | ||
+ | |||
+ | // Initial zeichnen | ||
+ | drawMandelbrot(Math.round(slider.Value())); | ||
</jsxgraph> | </jsxgraph> |