1
當我使用getImageData()函數來獲取圖像的數據與鉻,它表示未捕獲IndexSizeError:無法執行'CanvasRenderingContext2D''getImageData':源寬度0 這裏是我的代碼:HTML5畫布getImageData()無法工作
<!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;
for (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>
這怎麼可能happended?以及如何解決它?