Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IndexSizeError on drawImage on IE and Edge

I am finding that a certain code fails in Internet Explorer and Edge, but seems to work flawlessly in Chrome and Firefox:

var image = document.getElementById("myImage");
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
context.drawImage(image, 1, 0, 499, 278, 0, 0, 749, 417);
img {
  width: 300px;
  height: 200px;
}
<img id="myImage" src="https://image.ibb.co/bsANfm/emptyphoto.png" />

<canvas id="myCanvas" width="600" height="400"></canvas>

For some reason, the CanvasRenderingContext2D.drawImage() call fails in IE 11 and Edge 40.15063.674.0, where I'm getting an IndexSizeError exception. According to MDN, I should only be getting this error if the size of either the canvas or the source rectangle is 0, which is not the case here.

Could anyone shed some light into whether I'm doing something wrong here, or if there's some workaround available?

like image 263
unpollito Avatar asked Mar 07 '23 18:03

unpollito


2 Answers

I've found the culprit. Essentially, I'd been asking the browser to paint a section of the image from y=0 to y=278, but the image is only 275px high. IE and Edge seem not to like this and decide to throw an error. If I change the 278 in the snippet above to 275, it works:

var image = document.getElementById("myImage");
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
context.drawImage(image, 1, 0, 499, 275, 0, 0, 749, 417);
img {
  width: 300px;
  height: 200px;
}
<img id="myImage" src="https://image.ibb.co/bsANfm/emptyphoto.png" />

<canvas id="myCanvas" width="600" height="400"></canvas>
like image 177
unpollito Avatar answered Mar 10 '23 11:03

unpollito


I've just hit the same issue, but with a slightly different cause. I'm using DrawImage with a transform to change the shape of it. Source image is 1240x1754.

canvas_context.transform( -0.035, 0.07, 0, 1, 600 * 1.035, 30 + 600 * 0.07 );
canvas_context.drawImage( source_image, 0, 0, 1240, 1754, 0, 0, 600, 849 );

This doesn't work in IE, it once again fails with the IndexSizeError exception.

It appears that the problem is caused by the browser going slightly over the edge of the source image as it tries to transform the image, even though the source area specified is the dimensions of the source image. Coming in 1 pixel from the edge in all directions changes the last line to:

canvas_context.drawImage( source_image, 1, 1, 1238, 1752, 0, 0, 600, 849 );

which solves the problem.

like image 29
David Norman Avatar answered Mar 10 '23 11:03

David Norman