Public
Edited
Aug 3, 2023
Insert cell
Insert cell
PNGprecision = 5
Insert cell
DOM.download(() => rasterizeWhite(chart), undefined, "Save as PNG")
Insert cell
chart = {
const svg = d3.create("svg");
svg
.append("circle")
.attr("cx", 50)
.attr("cy", 50)
.attr("r", 25)
.style("fill", "purple");

svg.append("svg:image").attr("x", 100).attr("y", 100).attr(
"xlink:href",
"https://mirrors.creativecommons.org/presskit/buttons/88x31/svg/cc-zero.svg"
// await FileAttachment("cc0gris@3.svg").url() another methode, but gives the same result
);

return svg.node();
}
Insert cell
function rasterizeWhite(svg) {
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 * PNGprecision,
rect.height * PNGprecision
);
context.fillStyle = `rgba(255,255,255,0)`;
context.strokeStyle = "red";
context.fillRect(
0,
0,
rect.width * PNGprecision,
rect.height * PNGprecision
);
context.drawImage(
image,
0,
0,
rect.width * PNGprecision,
rect.height * PNGprecision
);
context.canvas.toBlob(resolve, "image/png", 1);
};
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

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