JSFiddle - React, Tailwind, and code Playground
by farhatdz
HTML
<canvas id="myCanvas" width="6029" height="6968"></canvas>
JavaScript
var canvas = document.getElementById('myCanvas'); //get canvas from html code via identity
var context = canvas.getContext('2d'); //get context of canvas
var imageObj = new Image(); //create image object
imageObj.src = 'gauteng.png'; //define the image of the image object
imageObj.onload = function() //trigger function after the image has loaded in image object
{
try
{
context.drawImage(imageObj,0,0); //draw the image object onto context of canvas
var imgd = context.getImageData(3200,3200,1,1); //get pixel at x coord 3200, and y coord 3200
var pix = imgd.data; //get the RGB values from pixel
// print out RGB values with alert
alert('R val= '+pix[0].toString()+ "\r\nG val= "+pix[1].toString()+"\r\nB val= "+pix[2].toString());
}
catch(err) //display error message if exception is thrown
{
alert(err.toString());
}
};
imageObj.onload = function() {
try
{
var inputFile = new XMLHttpRequest();
inputFile.open('get', 'gauteng.png', true); //open example file
inputFile.onreadystatechange = function()
{
if(inputFile.readyState==4) //document is ready to parse
{
context.drawImage(imageObj, 0, 0);
//pixel location from image
var imgd = context.getImageData(3200,3200,6029,6968);
var pix = imgd.data;
alert(pix[0].toString()+ " "+pix[1].toString()+" "+pix[2].toString());
}
}
inputFile.send(null); //close file after finished
}
catch(err){ alert(err.toString());}
};