Skip to content

Commit be70669

Browse files
committed
better method to horizontal align the title
1 parent 236e3c7 commit be70669

File tree

1 file changed

+26
-7
lines changed

1 file changed

+26
-7
lines changed

src/components/legend/draw.js

Lines changed: 26 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,30 @@ module.exports = function draw(gd, opts) {
5454
}
5555
};
5656

57+
//After legend dimensions are calculated the title can be aligned horizontally left, center, right
58+
function horizontalAlignTitle(titleEl, legendObj, bw) {
59+
if ((legendObj.title.side !== 'top center') && (legendObj.title.side !== 'top right')) return;
60+
61+
var font = legendObj.title.font;
62+
var lineHeight = font.size * LINE_SPACING;
63+
var titleOffset = 0;
64+
var textNode = titleEl.node();
65+
66+
var width = Drawing.bBox(textNode).width; //width of the title text
67+
68+
if(legendObj.title.side === 'top center') {
69+
titleOffset = 0.5 * (legendObj._width - 2 * bw - 2 * constants.titlePad - width);
70+
} else if(legendObj.title.side === 'top right') {
71+
titleOffset = legendObj._width - 2 * bw - 2 * constants.titlePad - width;
72+
}
73+
74+
svgTextUtils.positionText(titleEl,
75+
bw + constants.titlePad + titleOffset,
76+
bw + lineHeight
77+
);
78+
}
79+
80+
5781
function drawOne(gd, opts) {
5882
var legendObj = opts || {};
5983

@@ -196,7 +220,7 @@ function drawOne(gd, opts) {
196220

197221
// re-calculate title position after legend width is derived. To allow for horizontal alignment
198222
if(title.text) {
199-
textLayout(titleEl, scrollBox, gd, legendObj, MAIN_TITLE);
223+
horizontalAlignTitle(titleEl, legendObj, bw);
200224
}
201225

202226
if(!inHover) {
@@ -667,18 +691,13 @@ function computeTextDimensions(g, gd, legendObj, aTitle) {
667691
// approximation to height offset to center the font
668692
// to avoid getBoundingClientRect
669693
if(aTitle === MAIN_TITLE) {
670-
var titleOffset = 0;
671694
if(legendObj.title.side === 'left') {
672695
// add extra space between legend title and itmes
673696
width += constants.itemGap * 2;
674-
} else if(legendObj.title.side === 'top center') {
675-
if(legendObj._width) titleOffset = 0.5 * (legendObj._width - 2 * bw - 2 * constants.titlePad - width);
676-
} else if(legendObj.title.side === 'top right') {
677-
if(legendObj._width) titleOffset = legendObj._width - 2 * bw - 2 * constants.titlePad - width;
678697
}
679698

680699
svgTextUtils.positionText(textEl,
681-
bw + constants.titlePad + titleOffset,
700+
bw + constants.titlePad,
682701
bw + lineHeight
683702
);
684703
} else { // legend item

0 commit comments

Comments
 (0)