Public
Edited
May 29, 2024
10 stars
Insert cell
Insert cell
Insert cell
{
const {naturalWidth: imgWidth, naturalHeight: imgHeight} = image;
const width = 600;
const height = width / imgWidth * imgHeight;
const minScale = width / imgWidth;

const canvas = d3.create("canvas")
.attr("width", width)
.attr("height", height)
.style("border", "1px solid #aaa");
const ctx = canvas.node().getContext("2d");

const onZoom = ({transform}) => {
const dx = transform.applyX(0);
const dy = transform.applyY(0);
const dw = transform.applyX(imgWidth);
const dh = transform.applyY(imgHeight);
ctx.clearRect(0, 0, width, height);
ctx.drawImage(image, dx, dy, dw - dx, dh - dy);
};
const zoom = d3.zoom().on("zoom", onZoom);
if(options.includes("set_scale_extent")) zoom.scaleExtent([minScale, 1]);
if(options.includes("set_translate_extent")) zoom.translateExtent([[0, 0], [imgWidth, imgHeight]]);
canvas.call(zoom);
if(options.includes("set_initial_scale")) zoom.scaleTo(canvas, minScale);
// No-op zoom to trigger the zoom handler.
else zoom.transform(canvas, d3.zoomTransform(canvas));
return canvas.node();
}
Insert cell
Insert cell
image = {
const img = new Image;
//img.crossOrigin = true; // Only need if we read from the target canvas.
img.src = imageSource;
await img.decode();
return img;
}
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