Reputation: 365
This snippet is based on CANVAS, it does convert image to grey scale and then apply some color overlay on image,it does proper work on Mozilla Firefox but not in chrome. In chrome it will give me an error message.
Uncaught DOMException: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The canvas has been tainted by cross-origin data.
Kindly provide me some solution,
Thanks in advance.
<script>
function tintImage(imgElement, tintColor) {
// create hidden canvas (using image dimensions)
var canvas = document.createElement("canvas");
canvas.width = imgElement.offsetWidth;
canvas.height = imgElement.offsetHeight;
var ctx = canvas.getContext("2d");
ctx.drawImage(imgElement, 0, 0);
var map = ctx.getImageData(0, 0, 1000, 1000);
var imdata = map.data;
// convert image to grayscale
var r, g, b, avg;
for (var p = 0, len = imdata.length; p < len; p += 4) {
r = imdata[p];
g = imdata[p + 1];
b = imdata[p + 2];
avg = Math.floor((r + g + b) / 3);
imdata[p] = imdata[p + 1] = imdata[p + 2] = avg;
}
ctx.putImageData(map, 0, 0);
// overlay filled rectangle using lighter composition
ctx.globalCompositeOperation = "overlay";
ctx.globalAlpha = 0.5;
ctx.fillStyle = tintColor;
ctx.fillRect(0, 0, canvas.width, canvas.height);
// replace image source with canvas data
imgElement.src = canvas.toDataURL();
}
/// some buttons for testing the demo
var redBtt = document.createElement("button");
redBtt.appendChild(document.createTextNode("Red"));
redBtt.onclick = function() {
tintImage(
document.getElementById('myImage'),
"#d60000"
);
}
document.body.appendChild(redBtt);
var grnBtt = document.createElement("button");
grnBtt.appendChild(document.createTextNode("Green"));
grnBtt.onclick = function() {
tintImage(
document.getElementById('myImage'),
"#000000"
);
}
document.body.appendChild(grnBtt);
var bluBtt = document.createElement("button");
bluBtt.appendChild(document.createTextNode("Blue"));
bluBtt.onclick = function() {
tintImage(
document.getElementById('myImage'),
"#050c8c"
);
}
document.body.appendChild(bluBtt);
</script>
<img id='myImage' src="https://yt3.ggpht.com/-gjxoCu8Fu3c/AAAAAAAAAAI/AAAAAAAAAAA/Uji17DdykF4/s900-c-k-no-mo-rj-c0xffffff/photo.jpg" />
<br/>
Upvotes: 0
Views: 1602
Reputation: 32859
This is more of an Cross Origin Resource Sharing (CORS) issue than, getImageData
function.
To resolve the issue, you need to ...
ꜰɪʀꜱᴛ
Set crossorigin
attribute for the image element, like so ...
<img crossorigin="anonymous" src="www.example.com/myImage.png">
ꜱᴇᴄᴏɴᴅ
Host the image on your local server or a website that supports cross origin resource sharing (ie. imgur.com)
Upvotes: 1