【问题标题】:InvalidStateError when drawing SVG to canvas in Firefox (works in Chrome)在 Firefox 中将 SVG 绘制到画布时出现 InvalidStateError(适用于 Chrome)
【发布时间】:2016-01-03 18:02:15
【问题描述】:

我的代码在 Chrome 中完美运行,但在 Firefox 中抛出错误。控制台说:

InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable

这是我的代码:

glitchElement('http://naratif.jvitasek.cz/images/past-no-b.svg', 'canvas1');
glitchElement('http://naratif.jvitasek.cz/images/medialni-no-b.svg', 'canvas2');
glitchElement('http://naratif.jvitasek.cz/images/subverz-no-b.svg', 'canvas3');
function glitchElement(sourceImg, idCanvas) {
    var canvas = document.getElementById(idCanvas),
        context = canvas.getContext('2d'),
        img = new Image(),
        w,
        h,
        offset,
        glitchInterval;

    img.src = sourceImg;
    img.onload = function() {
        init();
        window.onresize = init;
        redraw();
    };

    var init = function() {
        clearInterval(glitchInterval);
        canvas.width = w = window.innerWidth;
        offset = w * 0.1;
        canvas.height = h = ~~(230 * ((w - (offset * 2)) / img.width));
        glitchInterval = setInterval(function() {
            clear();
            console.log(offset);
            console.log(w - (offset*2));
            console.log(h);
            context.drawImage(img, 0, 0, img.width, 230, offset, 0, w - (offset * 2), h);
            glitchImg();
            setTimeout(function() {
                clear();
                redraw();
            }, randInt(100,130)); // doba, po kterou je obrazek glitchnut
        }, randInt(3000,7000)); // interval mezi kazdym glitchem
    };

    var clear = function() {
        context.rect(0, 0, w, h);
        context.fillStyle = "white";
        context.fill();
    };

    var glitchImg = function() {
        for (var i = 0; i < randInt(1, 7); i++) {
            var x = Math.random() * w;
            var y = Math.random() * h;
            var spliceWidth = w - x;
            var spliceHeight = randInt(5, h / 3);
            context.drawImage(canvas, 0, y, spliceWidth, spliceHeight, x, y, spliceWidth, spliceHeight);
            context.drawImage(canvas, spliceWidth, y, x, spliceHeight, 0, y, x, spliceHeight);
        }
    };

    var randInt = function(a, b) {
        return ~~(Math.random() * (b - a) + a);
    };

    function redraw() {
        context.drawImage(img, 0, 0, img.width, 230, offset, 0, w - (offset * 2), h);
    }
}

我读到这可能是 Firefox 中的一个错误,但我尝试了一些方法来解决这个问题(比如添加宽度/高度、canvg、...),但似乎没有什么对我有用。谁能提示我如何解决这个问题,以便代码也可以在 Firefox 中运行?

【问题讨论】:

标签: javascript css google-chrome firefox svg


【解决方案1】:

为了drawImage to work with an SVG image in Firefox,SVG 图像文件必须有一个根&lt;svg&gt; 元素,该元素同时具有宽度和高度属性,两者都不能是百分比。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-29
    • 2016-03-17
    • 2013-08-08
    • 2012-12-07
    • 1970-01-01
    • 2012-10-05
    • 2012-10-03
    • 1970-01-01
    相关资源
    最近更新 更多