问题
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?
回答1:
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>
来源:https://stackoverflow.com/questions/46914128/indexsizeerror-on-drawimage-on-ie-and-edge