JavaScript Raphael,通过不同的功能在矩形顶部添加文本

时间:2013-03-13 16:31:03

标签: javascript raphael

我想让函数B工作而不必将指令代码设置为函数A.用实际术语来说,在矩形的顶部显示文本。

在这个问题中,按钮A用于创建“纸张”和矩形(使用Raphael库)。按钮B用于在矩形顶部添加文本。 HTML代码如下所示:

<button onClick="func.A()">Func A</button>
<button onClick="func.B()">Func B</button>

JavaScript代码如下所示:

var func = (function functie($) {
    return { 
        A: function() {
            // Creates canvas 320 × 200 at 10, 50
            var paper = Raphael(10, 50, 320, 200);
            // Creates rectangle
            var bg = paper.rect(0, 0, 320, 200);
            // Sets the fill attribute of the circle to red (#f00)
            bg.attr("fill", "#f00");
            // Sets the stroke attribute of the circle to white
            bg.attr("stroke", "#fff");
        },
        B: function() {
            var t = paper.text(40, 15, "");
            t.attr('text',"new text here");
            t.attr();
        };
 })();

问题是,当函数B的指令代码(var t = paper.text(40,15,“”);等等)放在函数B中时,我尝试添加的文本赢了“ t被添加到矩形。

如果函数B的指令代码放在函数A中,那么它将起作用,但这不是我想要的。我想让函数B工作而不必将指令代码设置为函数A.

我希望这个问题足够明白。

1 个答案:

答案 0 :(得分:2)

当您在函数A中声明“var paper”时,该变量对于函数A是本地的。如果要在函数调用之间共享状态信息,则必须将状态信息存储在对象的属性中,而不是局部变量中。 :

var func = (function functie($) {
return { 
    paper: null,
    A: function() {
        // Creates canvas 320 × 200 at 10, 50
        this.paper = Raphael(10, 50, 320, 200);
        // Creates rectangle
        var bg = paper.rect(0, 0, 320, 200);
        // Sets the fill attribute of the circle to red (#f00)
        bg.attr("fill", "#f00");
        // Sets the stroke attribute of the circle to white
        bg.attr("stroke", "#fff");
    },
    B: function() {
        var t = this.paper.text(40, 15, "");
        t.attr('text',"new text here");
        t.attr();
    };
})();