Error Uncaught Domexception:

Asked

Viewed 179 times

0

Uncaught Domexception: Failed to execute 'getImageData' on 'Canvasrenderingcontext2d': The source width is 0.

But I’m doing the same getting the width of canvas, which is 664px;

    <canvas id="viewport" width="664px" height="664px"></canvas>
<script>

let canvas = document.getElementById('viewport'),
context = canvas.getContext('2d');

make_base();


   console.log("aqui "+imageData.data)
   numPixels = imageData.width * imageData.height;

  let count = 0;
  for ( let i = 0; i < numPixels; i++ ) {
      let r = pixels[ i * 4 ],
          g = pixels[ i * 4 + 1 ],
          b = pixels[ i * 4 + 2 ];

        if(r == 255 && g == 0 && b == 0){
          count++;
        }
  }

  alert("O numero de pixels vermelhor é :"+count);
}


</script>

1 answer

0


The problem is that you are calling the function make_base() before the image is loaded.

As the image loading process is asynchronous, you must call this function, only after full loading, for example:

loadPicture();

function loadPicture() {
    img = new Image();
    img.src = 'img/img.png';

    img.onload = function () {
        context.drawImage( img, 0, 0 );

        make_base();
    }
};
  • I did what you said, like in firefox no error appears, Chrome gives error and nor does the pixel count that strange

  • @tatah The count is not being performed because the condition r == 255 && g == 0 && b == 0 is not true. You can add console.log( r == 255 && g == 0 && b == 0 ) and check in the browser console.

  • Remembering that there are several shades of red. Including if the tone r: 255, g: 255, b: 254 is found, it will not be computed. Use a photo editor and create an image with the color (255,0,0), this way there will be no variations.

  • my console, keeps popping this error Domexception: Failed to execute 'getImageData' on 'Canvasrenderingcontext2d': The canvas has been tainted by cross-origin data.

  • @tatah This happens when you use an external image, for security measure, the browser blocks.

  • I’m using an image inside a folder

  • https://codepen.io/valdeir2000/pen/WzXPXr

  • Thanks, I didn’t know about Base64

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.