画布上的drawImage时INDEX_SIZE_ERR

时间:2014-02-05 13:10:59

标签: javascript exception canvas html5-canvas drawimage

我需要在画布上绘制一个Image对象,但我在Firefox和IE10中有一个INDEX_SIZE_ERR例外,但在Chrome和Safari中都没有... {/ p>

根据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

问题的根源是什么?

由于

2 个答案:

答案 0 :(得分:0)

您正在手动设置图像的宽度和高度(img.width = width; img.height = height;)。我真的不明白你为什么要这样做,但这可能是不必要的。

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

答案 1 :(得分:0)

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

如果你想在加载图像之前设置宽度和高度,你可以这样做:

var img = new Image(width, height);

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

没有必要这样做。只需像这样打电话给drawImage()

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

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

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

修改后的代码:

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;
}