繁体   English   中英

在画布上绘制图像时INDEX_SIZE_ERR

[英]INDEX_SIZE_ERR when drawImage on canvas

我需要在画布上绘制一个Image对象,但是在Firefox和IE10中有一个INDEX_SIZE_ERR异常,但在Chrome和Safari中却没有。

根据W3CIf one of the sw or sh arguments is zero, the implementation must raise an INDEX_SIZE_ERR exception.

这是导致问题的代码:

function writePhotoOnCanvas(data, width, height) {
    // Get the canvas
    var canvasGallery = document.getElementById("canvasGallery");
    // Clear the canvas
    canvasGallery.width = canvasGallery.width;
    // Get its context
    var ctxCapture = canvasGallery.getContext("2d");

    // Create an image in order to draw in the canvas
    var img = new Image();
    // Set image width
    img.width = width;
    // Set image height
    img.height = height;

    // To do when the image is loaded
    img.onload = function() {
        console.log("img.width="+img.width+", img.height="+img.height);
        console.log("width="+width+", height="+height+", canvasGallery.width="+canvasGallery.width+", canvasGallery.height="+canvasGallery.height);
        //  Draw the picture
        try {
            ctxCapture.drawImage(img, 0, 0, img.width, img.height, 0, 0, canvasGallery.width, canvasGallery.height);
        } catch(e) {
            console.error(e.message);
        }
    };

    // Set image content from specified photo
    img.src = data;
}

控制台显示:

img.width=640, img.height=480
width=640, height=480, canvasGallery.width=589, canvasGallery.height=440
Index or size is negative or greater than the allowed amount

问题的根源是什么?

谢谢

您正在手动设置图像的宽度和高度( img.width = width; img.height = height; )。 我不太了解您为什么要这样做,但可能没有必要。

这些应该根据您加载的图像数据自动计算。 尝试删除它们以查看数据的实际大小。

图像的widthheight只读属性,因此它们将导致代码在某些浏览器中中断。

如果您绝对希望在加载图像之前设置宽度和高度,则可以执行以下操作:

var img = new Image(width, height);

然后,您可以在加载图像后读取 img.widthimg.height (或读取img.naturalWidthimg.naturalHeight以获取原始尺寸)。

尽管没有必要这样做。 只需像这样调用drawImage()

ctxCapture.drawImage(img, 0, 0, canvasGallery.width, canvasGallery.height);

这将使用图像的完整尺寸,并将其缩放到canvasGallery的尺寸。

提示:如果您正在使用此功能加载多个图像,则需要在onload处理程序中与this交换img

修改后的代码:

function writePhotoOnCanvas(data, width, height) {

    var canvasGallery = document.getElementById("canvasGallery");
    var ctxCapture = canvasGallery.getContext("2d");

    /// setting width to clear does not work in all browser, to be sure:
    ctxCapture.clearRect(0, 0, canvasGallery.width, canvasGallery.height);

    var img = new Image();
    img.onload = function() {
        //  Draw the picture
        try {
            ctxCapture.drawImage(this, 0, 0,
                                     canvasGallery.width, canvasGallery.height);
        } catch(e) {
            console.error(e.message);
        }
    };

    // Set image content from specified photo
    img.src = data;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM