Newer
Older
fractals / src / FractalSVG.ts
@peter peter on 2 Oct 2019 2 KB Refactoring.
import { Polygon, Point } from "./Polygon";

function inwardSpiral(input:Polygon, scalar:number): Polygon
{
    const output = new Polygon();

    let a:Point;
    let b:Point;
    let cx: number;
    let cy: number;
    for(let i=0;i<input.length;i++)
    {
        a = input[i];
        b = input[(i+1)%input.length];

        cx = scalar * (b.x - a.x) + a.x;
        cy = scalar * (b.y - a.y) + a.y;

        output.push(new Point(cx, cy));
    }

    return output;
}

export function createInwardSpiral(input:Polygon, maxiterations:number, shrinkRate:number): Polygon[]
{
    const cycle:Polygon[] = [input];
    let pNext:Polygon;

    for(let i=0;i<maxiterations;i++)
    {
        pNext = inwardSpiral(input, shrinkRate);
        cycle.push(pNext);
        input = pNext;
    }

    return cycle;
}

function polygonToSVG(polygon:Polygon, cssStyle:string): string
{
    const svg = [`<polygon points="`];
    for(const corner of polygon)
    {
        svg.push(`${corner.x},${corner.y} `);
    }
    svg.push(`" style="${cssStyle}" />`);

    return svg.join("");
}

export function fractalToSVG(fractal:Polygon[][], sideLength:number): string
{
    const svg = [`<?xml version="1.0"?><svg xmlns="http://www.w3.org/2000/svg"
 xmlns:xlink="http://www.w3.org/1999/xlink" width="${sideLength}" height="${sideLength}"
 style="fill:none;stroke:purple;stroke-width:1">`];

    let colorStrength = 0;
    const initialColorStrength = 20;
    for(const segment of fractal)
    {
        colorStrength = initialColorStrength;
        for(const iteration of segment)
        {
            svg.push(polygonToSVG(iteration, `fill:rgb(0,0,${Math.floor(colorStrength)})`));
            colorStrength += (255-initialColorStrength)/segment.length;
        }
    }

    svg.push("</svg>");

    return svg.join("");
}

export function createSquare(side:number): Polygon
{
    const square = new Polygon();
    square.push(new Point(0,0));
    square.push(new Point(0,side));
    square.push(new Point(side,side));
    square.push(new Point(side,0));
    return square;
}

export function inwardSpiralFractal(shape:Polygon, iterations:number, shrinkRate:number): Polygon[][]
{
    const fractal = [
        createInwardSpiral(shape, iterations, shrinkRate),
    ];
    return fractal;
}