Published
Edited
Aug 10, 2020
Importers
2 stars
Insert cell
Insert cell
Insert cell
Insert cell
{
const canvas = html`<canvas width=${width + "px"} height="${height +
"px"}"></canvas>`;
const context = canvas.getContext("2d");

context.fillStyle = "steelblue";
context.beginPath();
for (let n of data) {
context.moveTo(n.x, n.y);
context.arc(n.x, n.y, n.r, 0, 2 * Math.PI);
}
context.fill();

return canvas;
}
Insert cell
data = Array.from(new Array(n)).map(d => ({
x: Math.random() * width,
y: Math.random() * height,
r: Math.random() * r
}))
Insert cell
n = 1000
Insert cell
r = 10
Insert cell
height = 600
Insert cell
// https://gist.github.com/callumlocke/cc258a193839691f60dd
function scaleCanvas(canvas, context) {
const width = canvas.width,
height = canvas.height;

console.log("w,h", width, height);
// assume the device pixel ratio is 1 if the browser doesn't specify it
const devicePixelRatio = window.devicePixelRatio || 1;

// determine the 'backing store ratio' of the canvas context
const backingStoreRatio =
context.webkitBackingStorePixelRatio ||
context.mozBackingStorePixelRatio ||
context.msBackingStorePixelRatio ||
context.oBackingStorePixelRatio ||
context.backingStorePixelRatio ||
1;

// determine the actual ratio we want to draw at
const ratio = devicePixelRatio / backingStoreRatio;

if (devicePixelRatio !== backingStoreRatio) {
// set the 'real' canvas size to the higher width/height
canvas.width = width * ratio;
canvas.height = height * ratio;

// ...then scale it back down with CSS
canvas.style.width = width + 'px';
canvas.style.height = height + 'px';
} else {
// this is a normal 1:1 device; just scale it simply
canvas.width = width;
canvas.height = height;
canvas.style.width = '';
canvas.style.height = '';
}

// scale the drawing context so everything will work at the higher ratio
context.scale(ratio, ratio);
}
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