MENU
Pixel Operations
getImageData(x,y,width,height).data returns the array of pixel values of the specified rectangular region on the canvas.
The array contains pixel values of the R-G-B-A components, left-to-right, then top-to-bottom.
Each value is an integer in the range [0,255].
While not a very efficient implementation, this example shows how each component of the individual pixels can be accessed.
Below, the image must be loaded over the same origin.
RESETRUNFULL
Below, the image must be loaded over the same origin.
RESETRUNFULL
<!DOCTYPE html>
<html>
<head></head>
<body>
<img id="image" src='/shared/puppy.jpg' width="300" height="300" /><br />
<canvas id="sourceCanvas" width="300" height="300" style="border:1px solid"></canvas>
<canvas id="targetCanvas" width="300" height="300" style="border:1px solid"></canvas><br />
<button onclick="displayImage()">Display Image</button>
<button onclick="grayscaleConvert()">Convert to Grayscale</button>
<script>
var scanvas = document.getElementById('sourceCanvas');
var sc = scanvas.getContext('2d');
var tcanvas = document.getElementById('targetCanvas');
var tc = tcanvas.getContext('2d');
function displayImage() {
var I = document.getElementById("image");
sc.drawImage(I, 0, 0, 300, 300);
}
function getPixelComponentValue(idp, x, y, c) {
return idp[((y * 300) + x) * 4 + c];
}
function grayscaleConvert() {
var I = document.getElementById("image");
var ImgData = sc.getImageData(0, 0, 300, 300);
var ImgDataPixels = ImgData.data;
console.log(ImgData.data);
for (y = 0; y < I.height; y++) {
for (x = 0; x < I.width; x++) {
let brightness =
(getPixelComponentValue(ImgDataPixels, x, y, 0) +
getPixelComponentValue(ImgDataPixels, x, y, 1) +
getPixelComponentValue(ImgDataPixels, x, y, 2)) / 3;
ImgDataPixels[((y * I.width) + x) * 4] = brightness;
ImgDataPixels[((y * I.width) + x) * 4 + 1] = brightness;
ImgDataPixels[((y * I.width) + x) * 4 + 2] = brightness;
}
}
tc.putImageData(ImgData, 0, 0);
}
</script>
</body>
</html>