<img src="https://i.imgur.com/tQQViaO.jpg" width=600 crossorigin=anonymous>
<canvas id="canvas"></canvas>
img, canvas {
display: inline block;
}
const
img = document.querySelector('img'),
canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d')
img.onload = () => makeItBlue(img)
function makeItBlue(img) {
// handy variable for the width and height of the image
const {width:w, height:h} = img;
// set the canvas to the same size as the image
canvas.width = w
canvas.height = h
// draw the image to the canvas and grab its raw ImageData
ctx.drawImage(img, 0, 0, w, h)
const imgData = ctx.getImageData(0,0,w,h)
// make every pixel significantly bluer
for (const pixel of pixels(imgData)) {
// how much space is left in the blue channel?
const dblue = 255 - pixel.b
// increase blue to take half of that space
pixel.b += dblue/2
}
// write the updated imageData to the canvas
ctx.putImageData(imgData,0,0)
}
/**
* Simple generator function that makes it easy to iterate
* over an ImageData array one pixel at a time and make
* updates
*
* NOTE: This function is designed to make modifying ImageData
* easier, so any changes made to the yielded pixel objects
* will be written back to the original ImageData object!
*
* @generator
* @param {ImageData} imgData
* @yields {Pixel} The next pixel in the image
*/
function* pixels(imgData) {
const pixels = imgData.data
for (let i=0; i<pixels.length/4; i++) {
const p = i*4
const pixel = {
r: pixels[p],
g: pixels[p+1],
b: pixels[p+2],
a: pixels[p+3]
}
yield pixel
// push pixel updates back to imgData object
pixels[p] = pixel.r
pixels[p+1] = pixel.g
pixels[p+2] = pixel.b
pixels[p+3] = pixel.a
}
}
/**
* @typedef {Object} Pixel
* @description A single pixel in an ImageData object
* @property {Number} r The red channel; 8-bit unsigned integer
* @property {Number} g The green channel; 8-bit unsigned integer
* @property {Number} b The blue channel; 8-bit unsigned integer
* @property {Number} a The alpha channel; 8-bit unsigned integer
*/
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.