Published
Edited
Aug 22, 2020
5 stars
Insert cell
Insert cell
Insert cell
imgURL = "https://source.unsplash.com/" + imageHash + "/" + 50 + "x" + 50
Insert cell
image = {
return new Promise((resolve, reject) => {
const image = new Image;
image.crossOrigin = 'anonymous';
image.src = imgURL;
image.onload = () => resolve(image);
image.onerror = reject;
});
}
Insert cell
imagePixel = {
// Get a reference to the image you want the pixels of and its dimensions
const w = image.width;
const h = image.height;
// Create a Canvas element
let canvas = document.createElement('canvas');
// Size the canvas to the element
canvas.width = w;
canvas.height = h;

// Draw image onto the canvas
let ctx = canvas.getContext('2d');
ctx.drawImage(image, 0, 0);

// Finally, get the image data as a Uint8ClampedArray
// ('data' is an array of RGBA pixel values for each pixel)
const raw = ctx.getImageData(0, 0, w, h);
// Let us get a normal array back to maniputate
const flatArray = Array.from(raw.data)
return flatArray;
}
Insert cell
pixels = {
const red = imagePixel.filter((x,i) => i%4 === 0)
const green = imagePixel.filter((x,i) => i%4 === 1)
const blue = imagePixel.filter((x,i) => i%4 === 2)
const alpha = imagePixel.filter((x,i) => i%4 === 3)
return red.map((_,i) => ({
y: image.height - Math.floor(i/image.width),
x: i%image.width,
red: red[i],
green: green[i],
blue: blue[i],
alpha: alpha[1],
shape: green[i] > blue[i] && green[i] > 200 ? 'green' : blue[i] > 200 ? 'blue' : 'other'
})).map(x=>({...x, hex: chroma(x.red, x.green, x.blue).hex()}))
}
Insert cell
vl.markSquare()
.data(pixels)
.encode(vl.x().fieldQ('x'),
vl.y().fieldQ('y'),
vl.color().fieldQ(vl.repeat('column')))
.width(200)
.repeat({column: ['red', 'green', 'blue']})
.render()
Insert cell
vl.markPoint({size: 400})
.data(pixels)
.encode(vl.x().fieldQ('x'),
vl.y().fieldQ('y'),
vl.color().fieldN('hex').scale(null),
vl.fill().fieldN('hex').scale(null),
vl.shape().fieldN('shape'))
.render()
Insert cell
vl.markPoint({size: 198})
.data(pixels)
.encode(vl.x().fieldQ('x'),
vl.y().fieldQ('y'),
vl.color().fieldN('hex').scale(null))
.render()
Insert cell
vl.markBar({size: 4})
.data(pixels)
.encode(vl.x().fieldQ('x'),
vl.y().fieldQ('y'),
vl.color().fieldN('hex').scale(null))
.render()
Insert cell
vl.markBar({size: 100})
.data(pixels)
.encode(vl.x().fieldQ('x'),
vl.y().fieldQ('y'),
vl.color().fieldN('hex').scale(null))
.render()
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
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