变量抛出'undefined'错误,无法弄清楚

时间:2012-01-12 16:28:40

标签: javascript raphael

我正在使用Raphael.js。每次我加载页面时都会收到错误消息:

con is undefined
x = con.x

我在Raphael文档中查找con,这就是我发现的:

var con = R._getContainer.apply(0, arguments),
    container = con && con.container,
    x = con.x,
    y = con.y,
    width = con.width,
    height = con.height;
    //...
这里明确定义了

con。这是我要加载的代码:

var paper = new Raphael(ele('canvas_container'), 500, 500);

window.onload = function() {
            var circle = paper.circle(100,100,100);
            for (i = 0; i < 5; i++) {
                var multiplier = i * 5;
                paper.circle(250 + (2 * multiplier), 100 + multiplier, 50 - multiplier);
            }
    }

有没有其他人收到此错误?这是拉斐尔版本中的一个错误吗?我还是有其他问题吗?

2 个答案:

答案 0 :(得分:10)

尝试在窗口的加载函数中移动纸张实例化:

window.onload = function() {
    var paper = new Raphael(ele('canvas_container'), 500, 500);
    var circle = paper.circle(100,100,100);
    for (i = 0; i < 5; i++) {
        var multiplier = i * 5;
        paper.circle(250 + (2 * multiplier), 100 + multiplier, 50 - multiplier);
    }
}

如果在DOM准备好之前尝试通过其id获取元素,getElementById将不会返回任何内容。如您所见[{3}},在空文档上尝试代码会显示相同的结果。

答案 1 :(得分:1)

Raphael.js希望页面上有一个硬编码的HTML元素,其名称为Raphael画布(即:“canvas_container”)。如果HTML元素是在运行时创建的(在JavaScript代码中动态生成),则会抛出此错误。

R._engine.create = function () {
    var con = R._getContainer.apply(0, arguments),
        container = con && con.container,
        x = con.x,
        y = con.y,
        width = con.width,
        height = con.height;
    if (!container) {
        throw new Error("SVG container not found.");
    }
    var cnvs = $("svg"),
        css = "overflow:hidden;",
        isFloating;
    x = x || 0;
    y = y || 0;
    width = width || 512;
    height = height || 342;
    $(cnvs, {
        height: height,
        version: 1.1,
        width: width,
        xmlns: "http://www.w3.org/2000/svg"
    });
    if (container == 1) {
        cnvs.style.cssText = css + "position:absolute;left:" + x + "px;top:" + y + "px";
        R._g.doc.body.appendChild(cnvs);
        isFloating = 1;
    } else {
        cnvs.style.cssText = css + "position:relative";
        if (container.firstChild) {
            container.insertBefore(cnvs, container.firstChild);
        } else {
            container.appendChild(cnvs);
        }
    }
    container = new R._Paper;
    container.width = width;
    container.height = height;
    container.canvas = cnvs;
    container.clear();
    container._left = container._top = 0;
    isFloating && (container.renderfix = function () {});
    container.renderfix();
    return container;
};