简体   繁体   中英

The canvas has been tainted by cross-origin data. local image

I have a local image and im trying to use getImageData() so I can loop through the pixels. But I keep getting this error.

"DOMException: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The canvas has been tainted by cross-origin data".

I have searched and can't find an answer that applies. any Help is appreciated. Again it's a local image.

 document.addEventListener("DOMContentLoaded",(e)=>{

const canvas = document.querySelector('#canvas');

const ctx = canvas.getContext('2d');
canvas.width = 600;
canvas.height = 400;

let imgObj = new Image()// this will load the image so I can put it on the canvas

imgObj.onload = function(e){
        let w = canvas.width;
        let nw = canvas.naturalWidth;
        let nh = canvas.height;
        let aspect = nw / nh;
        let h = w/aspect;
            ctx.drawImage(imgObj,0,0,w,nh)
     
      
}


  //My image is in a local file but I keep getting an error
  //The canvas has been tainted by cross-origin data.
   
    imgObj.src = 'img/Tooth1.png';
 

  let imgData1;
   const grayScale =  function(ev){

try {
    
    imgData1 = ctx.getImageData(0,0,canvas.width, canvas.height);

  let arr = imgData1.data;// get the image raw data array
   // set up loop to go through each pixel

   for(let i = 0; i<arr.length; i=i+4){// inc by 4 eveytime Cause 
    there are 4 values
        // red       blue      green  if 4th it would be alfa
      let ttl = arr[i] + arr[i+1] + arr[i+2];

     let avg = parseInt(ttl/3);

// if i set all three values to the same it will be some color of 
  grey
    arr[i] = avg;

    arr[i+1] = avg;

    arr[i+2] = avg;
   }
   } catch (error) {
    console.log(error)
   }

   imgData.data = arr;
    ctx.putImageData(imgData, 0,0);

}

canvas.addEventListener('click', grayScale);

 });

I had to set up a server and have the image stored there. then i could run through local host and it worked.

I found this link that answers the in more detail.

"Cross origin requests are only supported for HTTP." error when loading a local file

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM