Skip to content

Instantly share code, notes, and snippets.

@atharvashukla
Last active May 22, 2021 15:23
Show Gist options
  • Save atharvashukla/4db6949b4a6463f068ca4f13db0b912d to your computer and use it in GitHub Desktop.
Save atharvashukla/4db6949b4a6463f068ca4f13db0b912d to your computer and use it in GitHub Desktop.
Randomly generates arbitrary number of unique single color png/svg images.
// HOW TO USE
// ----------
//
// Setup:
// mkdir random-rgb; cd random-rgb; npm init -y; npm i canvas; mkdir imgs;
// Then place this file (random-rgb.js) into random-rgb folder (as created above), run:
// node random-rgb.js
//
// Configuring:
//
// Set DIRPATH to specify the directory to place the images in (ends with "/")
// Set KIND to "png" or "svg", TOTAL_IMAGES, WIDTH, and HEIGHT are self-explanatory
//
const DIRPATH = "./imgs/"
const KIND = "svg"
const TOTAL_IMAGES = 10
const WIDTH = 100;
const HEIGHT = 100;
const { createCanvas } = require("canvas");
const fs = require('fs')
const randomrgb = () =>
({ r: Math.round(Math.random() * 255), g: Math.round(Math.random() * 255), b: Math.round(Math.random() * 255) })
const randomSet = (n) => {
let rgbs = new Set();
while (rgbs.size !== n) {
rgbs.add(randomrgb())
}
return rgbs;
}
const rgbstr = (r, g, b) => `rgb(${r},${g},${b})`
const genpng = (r, g, b) => {
const canvas = createCanvas(WIDTH, HEIGHT)
const ctx = canvas.getContext("2d")
ctx.fillStyle = rgbstr(r, g, b)
ctx.fillRect(0, 0, WIDTH, HEIGHT)
return canvas.toBuffer("image/png")
}
const gensvg = (r, g, b) => `<svg xmlns="http://www.w3.org/2000/svg" width="${WIDTH}" height="${HEIGHT}">
<rect fill="${rgbstr(r, g, b)}" x="0" y="0" width="${WIDTH}" height="${HEIGHT}"></rect>
</svg>`
const main = (n) => {
randomSet(n).forEach(rgb => {
let rgbst = rgbstr(rgb.r, rgb.g, rgb.b)
fs.writeFileSync(
`${DIRPATH}${KIND === "png" ? `${rgbst}.png` : `${rgbst}.svg`}`,
KIND === "png" ? genpng(rgb.r, rgb.g, rgb.b) : gensvg(rgb.r, rgb.g, rgb.b)
)
})
}
main(TOTAL_IMAGES)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment