admin管理员组

文章数量:1315287

I'm brand new to Raphael, and I was wondering if there's a way I can draw a rect, and draw text inside of it and attach it somehow, so that when I move and scale the rect, the text moves and scales as well? If not, how could I achieve that effect?

I'm brand new to Raphael, and I was wondering if there's a way I can draw a rect, and draw text inside of it and attach it somehow, so that when I move and scale the rect, the text moves and scales as well? If not, how could I achieve that effect?

Share Improve this question asked Feb 7, 2012 at 22:05 CaptSaltyJackCaptSaltyJack 16.1k17 gold badges72 silver badges101 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

One way would be to use Sets like this:

var paper = Raphael("holder", 200, 200);
paper.setStart();
paper.rect(-50, -50, 100, 100);
paper.text(0, 0, "hello");
var st = paper.setFinish();
st.transform("r10").translate(100, 100);

(On JSFiddle)

Tip: Note that you have to track the rotation axis on your own if you're not using 0,0 as the center. I personally like to keep it at 0,0 and then translate it to wherever I want.

You can try using this instead. The size of the rectangle gets resized as and when the text length increases.

var recttext = paper.set();
el = paper.rect(0, 0, 300, 200);
text = paper.text(0,10, "Hi... This is a test to check whether the rectangle dynamically changes its size.").attr({"text-anchor":"start",fill:'#ff0000',"font-size": 14});
text1=paper.text(0,30,"hi").attr({"text-anchor":"start",fill: '#ff0000',"font-size": 14});
recttext.push(el);
recttext.push(text);
recttext.push(text1);
alert(recttext.getBBox().width);
alert(recttext.getBBox().height);
var att = {width:recttext.getBBox().width,height:recttext.getBBox().height};
el.attr(att);
recttext.translate(700,400);

You can use Raphael's 'data' method to bind two elements together.

paper = Raphael(paper, 400, 400);
var circle = paper.circle(50, 50, 20)
.attr({
"fill": "#0ff"
})
.data("initialR", 20);

var labelize = function (shape, label) {
if (!label) {
    var label = "StackOverflow"
};
var label = paper.text(shape.attr("cx"), shape.attr("cy"), label)
    .attr({
    "opacity": 0
});
shape.data("label", label);

var hoverIn = function () {
    this.animate({
        "r": 100
    }, 500, "<>");
    this.data("label").animate({
        "opacity": 1
    }, 500);
};
var hoverOut = function () {
    this.animate({
        "r": this.data("initialR")
    }, 500, "<>");
    this.data("label").animate({
        "opacity": 0
    }, 500);
};
shape.hover(hoverIn, hoverOut, shape, shape);
return shape;
};

circle = labelize(circle, "CaptSaltyJack");

JSFiddle

本文标签: javascriptCan I attachbind text to elements in RaphaelStack Overflow