Created
May 10, 2023 10:52
-
-
Save vmfunc/9da6d2a93c0b15f434cab8a9e6226219 to your computer and use it in GitHub Desktop.
Spierpinski squares in node.js with canvas
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// nodejs Spierpinski squares script | |
// hangs after 8 recursions on my machine for some reason | |
const prompt = require('prompt-sync')(); | |
const { createCanvas, loadImage } = require('canvas'); | |
const n = parseInt(prompt('Number (int) to generate: ')); | |
// Creating tile | |
const canvas = createCanvas(800, 800); | |
const ctx = canvas.getContext('2d'); | |
// Colors | |
const colors = ['#000000', '#FFFFFF']; | |
// Recursive func to draw fractal | |
function drawFractal(x, y, size, depth) { | |
if (depth === 0) { | |
ctx.fillStyle = colors[depth % 2]; | |
ctx.fillRect(x, y, size, size); | |
} else { | |
// Call recursive for the 4 inside squares | |
const newSize = size / 3; | |
drawFractal(x, y, newSize, depth - 1); | |
drawFractal(x + newSize, y, newSize, depth - 1); | |
drawFractal(x + 2 * newSize, y, newSize, depth - 1); | |
drawFractal(x, y + newSize, newSize, depth - 1); | |
drawFractal(x + 2 * newSize, y + newSize, newSize, depth - 1); | |
drawFractal(x, y + 2 * newSize, newSize, depth - 1); | |
drawFractal(x + newSize, y + 2 * newSize, newSize, depth - 1); | |
drawFractal(x + 2 * newSize, y + 2 * newSize, newSize, depth - 1); | |
} | |
} | |
drawFractal(0, 0, canvas.width, n); | |
// Save picture | |
const fs = require('fs'); | |
const out = fs.createWriteStream(__dirname + '/fractal.png'); | |
const stream = canvas.createPNGStream(); | |
stream.pipe(out); | |
out.on('finish', () => console.log('Generated fractal successfully.')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment