diff --git a/src/canvas/draw.js b/src/canvas/draw.js new file mode 100644 index 0000000..8cd8e38 --- /dev/null +++ b/src/canvas/draw.js @@ -0,0 +1,34 @@ +import { coords2complex } from 'src/utils/math/complex' +import { checkSeries } from 'src/utils/math/mandelbrot' + +function calcDataPos(x, y, w) { + return (x * w + y) * 4 +} + +/** + * Draw mandelbrot on image + * @param {ImageData} image Image from canvas + * @return {ImageData} Resulting image + */ +export function drawMandelbrot(image) { + const width = image.width, + height = image.height + let c, pos + + // big step because pretty slow + for (let x = 0; x < width; x += 20) { + for (let y = 0; y < height; y += 10) { + c = coords2complex(x, y, width, height) + if (checkSeries(c)) { + pos = calcDataPos(x, y, width) + + // black + image.data[pos] = 0 + image.data[pos + 1] = 0 + image.data[pos + 2] = 0 + } + } + } + + return image +} diff --git a/src/components/App.svelte b/src/components/App.svelte index b19f3b3..7496606 100644 --- a/src/components/App.svelte +++ b/src/components/App.svelte @@ -1,5 +1,13 @@ - + - + + +{#if width !== undefined && height !== undefined} + +{/if} diff --git a/src/components/Canvas.svelte b/src/components/Canvas.svelte new file mode 100644 index 0000000..043dcef --- /dev/null +++ b/src/components/Canvas.svelte @@ -0,0 +1,29 @@ + + + + + diff --git a/src/utils/math/complex.js b/src/utils/math/complex.js new file mode 100644 index 0000000..0700f58 --- /dev/null +++ b/src/utils/math/complex.js @@ -0,0 +1,33 @@ +export function coords2complex(x, y /*, sx, sy*/, sw, sh) { + return new Complex(x - sw / 2, sh - y - sh / 2) +} + +/** + * Complex number + * + * `Complex(5, 6)` is 5x + 6i + */ +export class Complex { + constructor(x, i = 0) { + this.x = x + this.i = i + } + add(c) { + return new Complex(this.x + c.x, this.i + c.i) + } + sub(c) { + return new Complex(this.x - c.x, this.i - c.i) + } + abs() { + return Math.sqrt(Math.pow(this.x) + Math.pow(this.i)) + } + eq(c) { + return this.x === c.x && this.i === c.i + } + pow2() { + return new Complex( + Math.pow(this.x, 2) - Math.pow(this.i, 2), + 2 * this.x * this.i + ) + } +} diff --git a/src/utils/math/mandelbrot.js b/src/utils/math/mandelbrot.js new file mode 100644 index 0000000..374a24c --- /dev/null +++ b/src/utils/math/mandelbrot.js @@ -0,0 +1,27 @@ +import { Complex } from 'src/utils/math/complex.js' + +const R = 2, + N = 1000, + z0 = new Complex(0) + +/** + * Check if all series elements < 2 + * + * Series: z^2 + c + * + * @param {Complex} c Point + * @return {Boolean} Result + */ +export function checkSeries(c) { + let tmp = z0.add(c) + + for (let i = 1; i < N; i++) { + if (tmp.abs() >= R) { + return false + } + + tmp = tmp.pow2().add(c) + } + + return true +}