so obviously this is quite a problem with some browsers, because I googled a number of hits regarding the "canvas gets tainted" mumbo jumbo when you try and get pixel data from canvas images, like :
var pix = context.getImageData(3200,3200,1,1).data;
So far I already tried the crossorigin = '' and XMLHttpRequest, but I still get the same problem. Then again, I don't know if I'm implementing it wrong and just being a noob. I will greatly appreciate it if someone could please help me with this problem. Struggling with it 1.5 days, before turning to a forum question as last resort. Note that my code works for Firefox browsers, but not for Chrome... It his crucial that my implementation has cross-browser functionality. This is a small javascript code snipped I extracted from my main project to isolate, and try and fix, the problem:
<html>
<head>
</head>
<body>
<canvas id="myCanvas" width="6029" height="6968"></canvas>
<script> <!-- Javascript section-->
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());
}
};
</script>
</body>
</html>
I can also include my approach for the XMLHttpRequest:
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());}
};
Thank you in advance.
when it is cross origin and you are working with canvas many issues are resolved by this:
imageObj.crossOrigin = 'anonymous';
// crossOrigin attribute has to be set before setting src.
Hope it helps
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.