Published
Edited
Nov 22, 2019
6 stars
Insert cell
Insert cell
{
const context = DOM.context2d(imagedata.width, imagedata.height / 2);
const img1 = rainbowify(imagedata, context, 1);
context.putImageData(img1, 0, 0);
const img2 = rainbowify(imagedata, context, 2);
context.putImageData(img2, imagedata.width, 0);
yield context.canvas;
}
Insert cell
function rainbowify(input, context, mode) {
const output = context.createImageData(input.width, input.height);

for (let i = 0; i < input.data.length; i += 4) {
const oldPixel = [
input.data[i + 0],
input.data[i + 1],
input.data[i + 2],
input.data[i + 3]
];
const nextPixel = findClosestPaletteColor(oldPixel, mode);
output.data[i + 0] = nextPixel[0];
output.data[i + 1] = nextPixel[1];
output.data[i + 2] = nextPixel[2];
output.data[i + 3] = nextPixel[3];
}

return output;
}
Insert cell
function findClosestPaletteColor([r, g, b, a], mode) {
// "length" of color vec
const l = Math.hypot(r, g, b);
// maximal distance use to normalize
const m = Math.hypot(255, 255, 255);

let rgbString;
if (mode === 1) {
rgbString = d3.interpolateTurbo(l / m);
} else {
rgbString = d3.interpolateRainbow(l / m);
}
// const rgbString = d3.interpolateSinebow(l / m);

// rgb string to components array
const [nextR, nextG, nextB] = rgbString
.replace(/rgb\(|/, '')
.split(',')
.map(n => parseInt(n));

return [nextR, nextG, nextB, 255];
}
Insert cell
imagedata = imagedataFromImg(image)
Insert cell
function ix(i, j) {
return (j * imagedata.width + i) * 4;
}
Insert cell
function imagedataFromImg(img) {
const canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
const context = canvas.getContext('2d');
context.drawImage(img, 0, 0, img.width, img.height);
return context.getImageData(0, 0, img.width, img.height);
}
Insert cell
Insert cell
Insert cell
d3 = require( "d3-scale-chromatic@1")
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