Canvas - IndexSizeError: Index or size is negative or greater than the allowed amount

前端 未结 4 970
醉酒成梦
醉酒成梦 2020-12-15 16:41

So in Firefox I\'m getting this error in the console when using drawImage on a canvas element.

\"IndexSizeError: Index or size is negative or greater than t         


        
相关标签:
4条回答
  • 2020-12-15 17:23

    When you are using clipping you need to make sure that the source region is within the image (not necessary for target as this will be clipped by canvas).

    So if you add restriction control it should work. Here is one way of doing this (before using the clipping functionality of drawImage):

    if (w > _config.canvasWidth) w = _config.canvasWidth;
    if (h > _config.canvasHeight) h = _config.canvasHeight;
    
    _cache.ctx.drawImage(_cache.canvas, 0, 0, w, h,
                          0, 0, _config.canvasWidth, _config.canvasHeight);
    

    Modified fiddle here.

    Tip 1:
    Normally this also applies to x and y but as these are 0 here there is no need to check.

    Tip 2:
    If you need the image to be drawn narrower than you need to instead of changing source region, change the target region.

    0 讨论(0)
  • 2020-12-15 17:27

    To help others, I had the same problem in canvas and I solve taking account on image load, for example :

    var image = new Image();
    image.crossOrigin = "use-credentials";
    image.onload = function(){
        // here canvas behavior
    };
    image.src = imgSrc;
    
    0 讨论(0)
  • 2020-12-15 17:37

    Width and Height of image you draw when you specify size values should be larger or equal to 1. As well for performance advantages floor all values you pass to it.
    If width and/or height is 0, it will result in:

    IndexSizeError: Index or size is negative or greater than the allowed amount
    

    In Firefox:

    width = Math.max(1, Math.floor(width));
    height = Math.max(1, Math.floor(height));
    ctx.drawImage(image, x, y, width, height);
    
    0 讨论(0)
  • 2020-12-15 17:40

    I had the same problem but in IE and Safari. There were three things in particular that I had to fix:

    1) I had to set the width and height of the image manually.

    var image = new Image();
    ...
    image.width = 34;
    image.height = 34;
    

    2) I had to avoid using negative offset when creating ol.style.Icon. In this case I had to change my SVG icon, but that pretty much depends to your icon. So this would cause exception because of the negative offset:

    var icon = new ol.style.Style({
        "image": new ol.style.Icon({
            ...
            "offset": [0, -50]
        })
    });
    

    3) I had to round the width and height values. As some of them were calculated dynamically, I had values like 34.378 which were causing problems. So I had to round them and pass the Integer value.

    0 讨论(0)
提交回复
热议问题