此错误的另一个原因是源图像的尺寸太大;它们超出了实际的图像尺寸。发生这种情况时,您会在 IE 中看到此错误,但不会在 Chrome 或 Firefox 中看到。
假设您有一个 150x150 的图像:
var imageElement = ...;
然后,如果您尝试使用更大的源尺寸来绘制它:
var sourceX = 0;
var sourceY = 0;
var sourceWidth = 200; // Too big!
var sourceHeight = 200; // Too big!
canvasContext.drawImage(imageElement,
sourceX, sourceY, sourceWidth, sourceHeight, // Too big! Will throw INDEX_SIZE_ERR
destX, destY, destWidth, destHeight);
这将在 IE 上抛出 INDEX_SIZE_ERR。(在撰写本文时,最新的 IE 是 IE11。)
修复只是限制源尺寸:
var sourceWidth = Math.min(200, imageElement.naturalWidth);
var sourceHeight = Math.min(200, imageElement.naturalHeight);
malloc4k 的回答暗示了这一点,但是,他认为这是因为 image.width 为零。我添加了这个新答案,因为图像宽度为零不一定是 IE 错误的原因。