just came into contact with canvas, to learn to convert a picture into black and white.
but can"t succeed all the time. I"m a little confused.
Thank you.
<body>
<canvas width="500" height="500"></canvas>
<script>
var canvas = document.querySelector("canvas");
var ctx = canvas.getContext("2d");
var image = new Image();
image.onload = function(){
ctx.drawImage(image,0,0);
makeGrayScale();
}
image.src = "images/background.jpg";
var makePixelGrayScale = function (r,g,b,a){
var y = ( 0.3 * r) + ( 0.59 * g ) + ( 0.11 * b);
return {r:y,g:y,b:y,a:y};
};
function makeGrayScale(){
var r,g,b,a;
var imageData = ctx.getImageData(0,0,500, 500)
var numPixels = imageData.data.length/4;
for (var i=0; i<numPixels; iPP){
r = imageData.data[i*4+0];
g = imageData.data[i*4+1];
b = imageData.data[i*4+2];
a = imageData.data[i*4+3];
pixel = makePixelGrayScale(r,g,b,a);
imageData.data[i*4+0] = pixel.r;
imageData.data[i*4+1] = pixel.g;
imageData.data[i*4+2] = pixel.b;
imageData.data[i*4+3] = pixel.a;
}
ctx.putImageData(imageData,0,0);
};
</script>
</body>
Uncaught DOMException: Failed to execute "getImageData" on "CanvasRenderingContext2D": The canvas has been tainted by cross-origin data.
at makeGrayScale (file:///C:/Users/yocor/Github/aboutCanvas/createCanvas.html:26:37)
at Image.image.onload (file:///C:/Users/yocor/Github/aboutCanvas/createCanvas.html:14:17)