【发布时间】: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 中运行?
【问题讨论】:
-
尝试在外部 SVG 元素上赋予非百分比值的 SVG 图像宽度和高度属性。
-
@RobertLongson 那么如果我在画布上绘图,我应该为该元素设置宽度和高度吗?我无法理解外部 SVG 元素的含义。
-
每个 svg 文件中的根
<svg>元素。所以让文件 -
@RobertLongson 问题是,当我查看我的源代码时,我没有看到任何 SVG 元素。我看到的只是画布,里面没有任何元素。
标签: javascript css google-chrome firefox svg