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

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more