秘訣は、テキスト要素を作成し、テキスト要素getBBox
の境界ボックスを取得するために使用することです。これにより、寸法x
とy
値が提供されます。
ここに例とデモがあります。
// Create Raphael and circle set
var Paper = new Raphael('canvas', 300, 300),
circles = Paper.set();
// Add circles to canvas, setting the tooltip text as a
// data attribute
circles.push(
Paper.circle(100, 150, 25).data('tooltip', 'Here is some text'),
Paper.circle(200, 150, 25).data('tooltip', 'And here is \nsome longer text')
);
// Some base styles
circles.attr({
fill: 'red',
stroke: 0
});
// Positioning of the tooltip box
var margin = 10,
padding = 5;
// Hover functions
circles.hover(
// On hover, create and show tooltip
function() {
// If the tooltip already exists on the element, simply
// show it. If it doesn't then we need to create it.
if (this.tooltip && this.tooltip.box) {
this.tooltip.show();
this.tooltip.box.show();
} else {
// Get the x and y positions.
// We get the 'true y' by deducting the radius
var x = this.attr('cx'),
y = this.attr('cy') - this.attr('r');
// Create the tooltip text, attaching it to the
// circle itself
this.tooltip = Paper.text(x, y, this.data('tooltip'));
// Calculate the bounding box of our text element
var bounds = this.tooltip.getBBox();
// Shift the text element in to correct position
this.tooltip.attr({
// At this point `y` is equal to the top of the
// circle arc. When creating a text element, the
// `x` and `y` values are center points by default,
// so by deducting half the height we can fake
// a bottom align. Finally deducting our `margin`
// value creates the space between the circle and
// the tooltip.
y: y - (bounds.height / 2) - margin,
fill: '#fff'
});
// Create the tooltip box, again attaching it to the
// circle element.
//
// The `x`, `y` and dimensions are dynamically calculated
// using the text element's bounding box and margin/padding
// values.
//
// The `y` value again needs some special treatment,
// creating the fake bottom align by deducting half the
// text element's height. We then adjust the `y` further
// by deducting the sum of the `padding` and `margin`.
// The `margin` value is needed to create space between
// the circle and the tooltip, and the `padding` value
// shifts the box a little higher to create the illusion of
// padding.
//
// Try adjusting the `margin` and `padding` values.
this.tooltip.box = Paper.rect(bounds.x - padding, bounds.y - (bounds.height / 2) - (padding + margin), bounds.width + (padding * 2), bounds.height + (padding * 2));
// Style the box and put it behind text element
this.tooltip.box.attr({
fill: '#000',
stroke: 0
}).toBack();
}
},
// On hover out, hide previously created tooltip
function() {
// Hide the tooltip elements
this.tooltip.box.hide();
this.tooltip.hide();
}
);