Uncaught Error DOMException:

0
  

Uncaught DOMException: Failed to execute 'getImageData' on   'CanvasRenderingContext2D': The source width is 0.

But I'm doing the same thing to receive the canvas width, 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>
    
asked by anonymous 27.03.2018 / 13:00

1 answer

0

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

As the process of loading the image is asynchronous, you should 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();
    }
};
    
27.03.2018 / 14:23