Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Raphael, adding text on top of rectangle through different functions

I want to let function B work without having set the instruction code to function A. In praktical terms, to show text on top of a rectangle.

In this question Button A is used for creating the 'paper' and a rectangle(which uses the Raphael library). Button B for adding text on top of the rectangle. The HTML code looks like this:

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

The JavaScript code looks like this:

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();
        };
 })();

The problem is that when the instruction code of function B (var t = paper.text(40, 15, ""); and so on), are placed in function B, that the text i try to add won't be added to the rectangle.

If the instruction code of function B are placed in function A, then it will work, but this is not what i want. I want to let function B work without having set the instruction code to function A.

I hope this problem is clear enough to understand.


1 Answers

When you declare "var paper" in function A, that variable is local to function A. If you want to share state information between function calls, you have to store the state information in properties of your object, rather than local variables:

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();
    };
})();
like image 178
Adrian Avatar answered Jul 01 '26 06:07

Adrian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!