Published
Edited
Jul 22, 2021
1 fork
2 stars
Insert cell
Insert cell
Insert cell
Insert cell
canvas = html`<canvas>`
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
w = image.naturalWidth
Insert cell
h = image.naturalHeight
Insert cell
Insert cell
ctx = canvas.getContext("2d")
Insert cell
{
canvas.width = w
canvas.height = h
ctx.drawImage(image, 0, 0, w, h) // drawImage(image, dx, dy, dWidth, dHeight)

const imageData = ctx.getImageData(0, 0, w, h)
// 👇 call the rgbSplit funciton with the imageData we got from the canvas context with offset values
const updatedImageData = rgbSplit(imageData, {
rOffset: rOffsetInput,
gOffset: gOffsetInput,
bOffset: bOffsetInput
})
// ctx.putImageData(updatedImageData, 0, 0)
ctx.putImageData(updatedImageData, 0, 0)
// view the data
return imageData
}
Insert cell
Insert cell
function rgbSplit(imageData, options) {
// destructure the offset values from options, default to 0
const { rOffset = 0, gOffset = 0, bOffset = 0 } = options
// clone the pixel array from original imageData
const originalArray = imageData.data
// calling the Uint8ClampedArray constructor and passing it the original color array
const newPixels = new Uint8ClampedArray(originalArray)
// loop through every pixel and assign values to the offseted position
// four values in that array represent one pixel...so we are setting the increment expression to be i += 4.
for (let i = 0; i < originalArray.length; i += 4) {
newPixels[i + 0 + rOffset * 4] = originalArray[i + 0]; // 🔴
newPixels[i + 1 + gOffset * 4] = originalArray[i + 1]; // 🟢
newPixels[i + 2 + bOffset * 4] = originalArray[i + 2]; // 🔵
}
// return a new ImageData object
return new ImageData(newPixels, imageData.width, imageData.height);
}

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