Published
Edited
Nov 28, 2020
1 fork
Importers
18 stars
Insert cell
Insert cell
Insert cell
Insert cell
randomArray = math.reshape(d3.shuffle(d3.range(200)), [10, 20])
Insert cell
imshow(randomArray, 20, d3.interpolateViridis)
Insert cell
Insert cell
tile = fetchTile({z: 13, x: 7262, y: 3232})
Insert cell
imshow(tile, 1.5, d => d3.interpolateBrBG(1-d))
Insert cell
Insert cell
function imshow(data, pixelSize, color) {
// Flatten 2D input array
const flat = [].concat.apply([], data);
// Color Scale & Min-Max normalization
const [min, max] = d3.extent(flat);
const normalize = d => ((d-min)/(max-min));
const colorScale = d => color(normalize(d));
// Shape of input array
const shape = {x: data[0].length, y: data.length};

// Set up canvas element
const canvas = DOM.canvas(shape.x, shape.y);
const context = canvas.getContext("2d");
canvas.style.width = `${shape.x * pixelSize}px`
canvas.style.height = `${shape.y * pixelSize}px`;
canvas.style.imageRendering = "pixelated";

// Draw pixels to the canvas
const imageData = context.createImageData(shape.x, shape.y);
flat.forEach((d, i) => {
let color = isNaN(d) ? {r: 0, g: 0, b: 0} : d3.color(colorScale(d));
imageData.data[i*4 ] = color.r;
imageData.data[i*4+1] = color.g;
imageData.data[i*4+2] = color.b;
imageData.data[i*4+3] = 255;
});
context.putImageData(imageData, 0, 0);

return canvas;
}
Insert cell
Insert cell
Insert cell
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