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 el = document.createElement("svg"); // el.setAttribute("width", sideLength.toString()); // el.setAttribute("height", sideLength.toString()); // el.setAttribute("style", "fill:none;stroke:purple;stroke-width:1"); const svg = [`<svg 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) { const polygonSvg = polygonToSVG(iteration, `fill:rgb(0,0,${Math.floor(colorStrength)})`); svg.push(polygonSvg); // el.append(polygonSvg); colorStrength += (255-initialColorStrength)/segment.length; } } // document.body.append(el); 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; }