Last active
April 3, 2024 20:51
-
-
Save cgcardona/772b5e040e26cb71a8d5 to your computer and use it in GitHub Desktop.
Get the RGBa value for each pixel in an image via <canvas>
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(document).ready(function (){ | |
// Get the image and canvas nodes | |
var img = $('#original_image')[0]; | |
var canvas = $('#original_canvas')[0]; | |
// confirm that the image has loaded | |
img.addEventListener("load", function() { | |
// set the canvas dimensions | |
canvas.width = img.width; | |
canvas.height = img.height; | |
//draw the original image to the canvas | |
canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height); | |
// loop over each pixel on the canvas and push it's RBGa value into an array | |
var original_image_color_data = [] | |
// First loop over the y axis (top to bottom) | |
for(var y = 0; y <= img.height; y++) { | |
// Now loop over the x axis (left to right) | |
for(var x = 0; x <= img.width; x++) { | |
// Get the RGBa value for that pixel | |
original_image_color_data.push(canvas.getContext('2d').getImageData(x, y, 1, 1).data); | |
} | |
} | |
// See the entire array of RGBa values | |
console.log(original_image_color_data); | |
}, false); | |
}); | |
~ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment