IndexSizeError on drawImage on IE and Edge

匿名 (未验证) 提交于 2019-12-03 01:00:01

问题:

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>


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!