Skip to content

Commit

Permalink
allow multiple lines of text in the line label (#129)
Browse files Browse the repository at this point in the history
allow multiple lines of text in the line label (#129)
  • Loading branch information
aoifef authored and benmccann committed Apr 30, 2019
1 parent 65c971c commit fdafa46
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 9 deletions.
2 changes: 1 addition & 1 deletion README.md
Expand Up @@ -141,7 +141,7 @@ Vertical or horizontal lines are supported.
// Whether the label is enabled and should be displayed
enabled: false,

// Text to display in label - default is null
// Text to display in label - default is null. Provide an array to display values on a new line
content: "Test label"
},

Expand Down
44 changes: 36 additions & 8 deletions src/types/line.js
Expand Up @@ -157,12 +157,25 @@ module.exports = function(Chart) {

ctx.font = chartHelpers.fontString(model.labelFontSize, model.labelFontStyle, model.labelFontFamily);
var textWidth = ctx.measureText(model.labelContent).width;
var textHeight = ctx.measureText('M').width;
var textHeight = model.labelFontSize;
model.labelHeight = textHeight + (2 * model.labelYPadding);

if (model.labelContent && chartHelpers.isArray(model.labelContent)) {
var labelContentArray = model.labelContent.slice(0);
var longestLabel = labelContentArray.sort(function(a, b) {
return b.length - a.length;
})[0];
textWidth = ctx.measureText(longestLabel).width;

model.labelHeight = (textHeight * model.labelContent.length) + (2 * model.labelYPadding);
// Add padding in between each label item
model.labelHeight += model.labelYPadding * (model.labelContent.length - 1);
}

var labelPosition = calculateLabelPosition(model, textWidth, textHeight, model.labelXPadding, model.labelYPadding);
model.labelX = labelPosition.x - model.labelXPadding;
model.labelY = labelPosition.y - model.labelYPadding;
model.labelWidth = textWidth + (2 * model.labelXPadding);
model.labelHeight = textHeight + (2 * model.labelYPadding);

model.borderColor = options.borderColor;
model.borderWidth = options.borderWidth;
Expand Down Expand Up @@ -255,12 +268,27 @@ module.exports = function(Chart) {
);
ctx.fillStyle = view.labelFontColor;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(
view.labelContent,
view.labelX + (view.labelWidth / 2),
view.labelY + (view.labelHeight / 2)
);

if (view.labelContent && chartHelpers.isArray(view.labelContent)) {
var textYPosition = view.labelY + view.labelYPadding;
for (var i = 0; i < view.labelContent.length; i++) {
ctx.textBaseline = 'top';
ctx.fillText(
view.labelContent[i],
view.labelX + (view.labelWidth / 2),
textYPosition
);

textYPosition += view.labelFontSize + view.labelYPadding;
}
} else {
ctx.textBaseline = 'middle';
ctx.fillText(
view.labelContent,
view.labelX + (view.labelWidth / 2),
view.labelY + (view.labelHeight / 2)
);
}
}

ctx.restore();
Expand Down

0 comments on commit fdafa46

Please sign in to comment.