Published
Edited
Jun 5, 2021
Importers
8 stars
Insert cell
Insert cell
Insert cell
canvasPlot(
Plot.dot(
{ length: 500 },
{ x: Math.random, y: Math.random, r: Math.random, fill: Math.random }
).plot()
)
Insert cell
Insert cell
{
// create a canvas
const width = 640;
const height = 400;
const context = DOM.context2d(width, height);
const canvas = context.canvas;

// paint the background and clip
context.save();
context.fillStyle = "steelblue";
context.fillRect(0, 0, width, height);
context.beginPath();
context.arc(width / 2, height / 2, 200, 0, 2 * Math.PI);
context.clip();
context.globalCompositeOperation = "luminosity";

// paint the plot on top
await canvasPlot(
Plot.dot(
{ length: 500 },
{ x: Math.random, y: Math.random, r: Math.random, fill: Math.random }
).plot({ style: { background: "transparent" }, x: { axis: null } })
).then((im) => (context.drawImage(im, 0, 0, width, height), canvas));

// then paint a string
context.restore();
context.fillStyle = "white";
context.textAlign = "center";
context.fillText("Hello, Plot", width / 2, height / 2);

return canvas;
}
Insert cell
canvasPlot = async (
plot,
style = html`<style>.plot{display:block;font:10px system-ui,sans-serif;background:#fff;height:auto;height:intrinsic;max-width:100%}.plot text{white-space:pre}</style>`,
dpi = 2
) => {
const { width, height } = plot.viewBox.baseVal;
const context = DOM.context2d(width, height, dpi);
const im = new Image();
im.width = width;
im.height = height;

plot.setAttribute("xmlns", "http://www.w3.org/2000/svg");
plot.appendChild(style);
im.src =
"data:image/svg+xml," +
encodeURIComponent(
plot.outerHTML.replace(
/https:[/][/].*?.observableusercontent.com\/.*?html/g,
""
)
);
return new Promise((resolve, reject) => {
im.onload = () => {
context.drawImage(im, 0, 0, width, height);
resolve(context.canvas);
};
setTimeout(() => reject(new Error()), 100);
});
}
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