Published
Edited
Apr 29, 2022
1 star
Insert cell
Insert cell
imageNames = d3.range(90, 101)
Insert cell
imageDatas = imageNames.map((id) => `https://map.infoicy.com?id=${id}`)
Insert cell
generatedCodes = Promise.all(
imageDatas.map((url) =>
qr.toString(url, {
margin: 2
})
)
)
Insert cell
viewof clicks = Inputs.button("Download generated QR Codes")
Insert cell
Insert cell
mutable debug = []
Insert cell
{
if (clicks) {
const elements = document.querySelectorAll(".wrapper svg");
mutable debug = [elements].concat(mutable debug);
elements.forEach((element, i) => {
mutable debug = [
"trying to include element, " + i,
element.outerHTML
].concat(mutable debug);

rasterize(element, imageNames[i]);
});
return "clicked";
}
}
Insert cell
function saveAs(uri, filename) {
// create link
var link = document.createElement("a");
if (typeof link.download === "string") {
document.body.appendChild(link); // Firefox requires the link to be in the body
link.download = filename;
link.href = uri;
link.click();
document.body.removeChild(link); // remove the link when done
} else {
location.replace(uri);
}
}
Insert cell
function rasterize(svg, name) {
let resolve, reject;
const promise = new Promise((y, n) => ((resolve = y), (reject = n)));
const image = new Image();
image.onerror = reject;
image.onload = () => {
const rect = svg.getBoundingClientRect();
const context = DOM.context2d(rect.width, rect.height);
context.drawImage(image, 0, 0, rect.width, rect.height);
context.canvas.toBlob(resolve);

let dt = context.canvas.toDataURL("image/png");
saveAs(dt, name);
};
image.src = URL.createObjectURL(serialize(svg));

return promise;
}
Insert cell
serialize = {
const xmlns = "http://www.w3.org/2000/xmlns/";
const xlinkns = "http://www.w3.org/1999/xlink";
const svgns = "http://www.w3.org/2000/svg";
return function serialize(svg) {
svg = svg.cloneNode(true);
const fragment = window.location.href + "#";
const walker = document.createTreeWalker(svg, NodeFilter.SHOW_ELEMENT);
while (walker.nextNode()) {
for (const attr of walker.currentNode.attributes) {
if (attr.value.includes(fragment)) {
attr.value = attr.value.replace(fragment, "#");
}
}
}
svg.setAttributeNS(xmlns, "xmlns", svgns);
svg.setAttributeNS(xmlns, "xmlns:xlink", xlinkns);
const serializer = new window.XMLSerializer();
const string = serializer.serializeToString(svg);
return new Blob([string], { type: "image/svg+xml" });
};
}
Insert cell
qr = require('https://unpkg.com/qrcode@1.4.4/build/qrcode.min.js')
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more