javascript - HTML5 canvas getImageData() can't work -


when use getimagedata() function data of image chrome, says uncaught indexsizeerror: failed execute 'getimagedata' on 'canvasrenderingcontext2d': source width 0. here code:

<!doctype html> <html> <head>     <title>canvastest</title> </head> <body> <img src="flower.jpg" hidden /> <canvas id="drawing" width="600" height="532">a drawing of something</canvas> <script type="text/javascript" >     var drawing = document.getelementbyid("drawing");     if (drawing.getcontext){         var context = drawing.getcontext("2d"),             image = document.images[0],             imagedata,data,             i,len,average,             red,blue,green,alpha;          image.onload = function(){             context.drawimage(image,0,0);         };          imagedata = context.getimagedata(0,0,image.width,image.height);         data = imagedata.data;          (i=0,len=data.length;i<len;i+=4){             red = data[i];             green = data[i+1];             blue = data[i+2];             alpha = data[i+3];              average = math.floor((red + green + blue) / 3);              data[i] = average;             data[i+1] = average;             data[i+2] = average;         }          imagedata.data = data;         context.putimagedata(imagedata,0,0);     } </script> </body> </html> 

how happended? , how fix it?

you attaching onload callback draw image canvas. fires once image loaded in dom , has fetched server. makes think of happens before try pull image data canvas?

that's problem when mixing synchronous , asynchronous code, , there numerous techniques getting around it. i'd bet money if set break point in debugger @ line draws image , line tries read latter trigger before former.

you either need put processing in onload handler (not recommended because of coupling) or use promise make sure code reads data runs after code writes it.


Comments

Popular posts from this blog

php - Invalid Cofiguration - yii\base\InvalidConfigException - Yii2 -

How to show in django cms breadcrumbs full path? -

ruby on rails - npm error: tunneling socket could not be established, cause=connect ETIMEDOUT -