<canvas id="canv"></canvas>
<div id="buttons">
<button id="download-png-button">Download PNG</button>
<button id="download-svg-button">Download SVG</button>
<button id="rejigger-button">Rejigger</button>
</div>
body {
margin: 0;
height: 100vh;
}
#buttons {
position: fixed;
top: 1rem;
right: 1rem;
}
View Compiled
const canv = document.querySelector("#canv");
const ctx = canv.getContext("2d");
const colorPalette = ["#9B2E69", "#D93750", "#E2724F", "#F3DC7B", "#4E9397"];
const rand = (max) => {
return Math.floor(Math.random() * max);
};
const makeRects = (maxX, maxY) => {
let rects = "";
for (let i = 0; i < 100; i++) {
rects += `
<rect
x="${rand(maxX + 50) - 50}"
y="${rand(maxY + 50) - 50}"
width="${rand(200) + 20}"
height="${rand(200) + 20}"
opacity="0.8${rand(10)}"
fill="${colorPalette[rand(5)]}"
/>
`;
}
return rects;
};
const makeSVG = () => {
const w = document.body.offsetWidth;
const h = document.body.offsetHeight;
const svg = `<svg width="${w}" height="${h}" id="svg" xmlns="http://www.w3.org/2000/svg">
<rect x="0" y="0" width="${w}" height="${h}" fill="${
colorPalette[rand(5)]
}" fill-opacity="0.5"/>
${makeRects(w, h)}
</svg>`;
window.globalSVGStore = svg;
return svg;
};
const setup = () => {
const v = canvg.Canvg.fromString(ctx, makeSVG());
v.start();
};
setup();
window.onresize = setup;
function download(filename, text) {
var pom = document.createElement("a");
pom.setAttribute(
"href",
"data:text/plain;charset=utf-8," + encodeURIComponent(text)
);
pom.setAttribute("download", filename);
if (document.createEvent) {
var event = document.createEvent("MouseEvents");
event.initEvent("click", true, true);
pom.dispatchEvent(event);
} else {
pom.click();
}
}
const downloadSvgButton = document.querySelector("#download-svg-button");
downloadSvgButton.addEventListener("click", () => {
download("art.svg", window.globalSVGStore);
});
const downloadPngButton = document.querySelector("#download-png-button");
downloadPngButton.addEventListener("click", () => {
canv.toBlob(function (blob) {
saveAs(blob, "art.png");
});
});
const rejiggerButton = document.querySelector("#rejigger-button");
rejiggerButton.addEventListener("click", () => {
setup();
});
This Pen doesn't use any external CSS resources.