Public
Edited
Nov 28, 2023
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
render = async function(img) {

const bitmap = await createImageBitmap(img)

canvas.width = w
canvas.height = h
// render the image on the canvas.
ctx.drawImage(img, 0, 0, w, h)

// svg overlay
const svg = d3.create('svg')
.attr('width', w)
.attr('height', h)

const data = pixelate({
image: image,
size: size,
context: ctx
})

mutable rgbValues = data

drawSvg({
colors: data,
size: size,
svg: svg
})

return svg.node()
}
Insert cell
Insert cell
dataRGB = rgbValues.map(d => d.rgb)
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function drawSvg (props) {
props = {
colors: null, // []
size: 10,
svg: null,
...props
}
const {colors, size, svg} = props
console.log('colors', colors)
const squares = svg.selectAll('rect')
.data(colors)
.join('rect')
.attr('x', d => d.x)
.attr('y', d => d.y)
.attr('width', size)
.attr('height', size)
.attr('fill', d => d.rgb)
.on('mouseover', function (event, d) {
// console.info('d', d)
mutable value = d.rgb
})
}

Insert cell
function pixelate (props) {
props = {
image: null,
size: 10,
context: null,
...props
}
const {image, size, context} = props
// Number of squares left-to-right and top-to-bottom.
const xSquares = image.naturalWidth / size
const ySquares = image.naturalHeight / size
let data = []
for (let x = 0; x < xSquares; x++) {
for (let y = 0; y < ySquares; y++) {
const rgba = context.getImageData(x * size, y * size, size, size).data
const len = rgba.length
const num = len / 4
let r = 0
let g = 0
let b = 0
// Sum the color values.
for (let i = 0; i < len; i += 4) {
r += rgba[i]
g += rgba[i + 1]
b += rgba[i + 2]
}
// Save the position and average color value.
data.push({
x: x * size,
y: y * size,
rgb: 'rgb(' + [
Math.round(r / num),
Math.round(g / num),
Math.round(b / num)
].join(',') + ')'
})
}
}
return data
}
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