Set maxWidth during title draw to avoid overflow

CanvasRenderingContext2D.fillText() accepts a fourth parameter called maxWidth that sets the maximum width of the drawn text, enforced by scaling the entire line.

This commit uses the title element's layout dimensions to set maxWidth and avoid overflow outside of the canvas.
This commit is contained in:
dylan-kerr 2016-09-23 22:05:54 +01:00 committed by Dylan Kerr
parent 84da2e0a10
commit fb302d5f00

View File

@ -158,7 +158,8 @@ module.exports = function(Chart) {
top = me.top,
left = me.left,
bottom = me.bottom,
right = me.right;
right = me.right,
maxWidth;
ctx.fillStyle = valueOrDefault(opts.fontColor, globalDefaults.defaultFontColor); // render in correct colour
ctx.font = titleFont;
@ -167,9 +168,11 @@ module.exports = function(Chart) {
if (me.isHorizontal()) {
titleX = left + ((right - left) / 2); // midpoint of the width
titleY = top + ((bottom - top) / 2); // midpoint of the height
maxWidth = right - left;
} else {
titleX = opts.position === 'left' ? left + (fontSize / 2) : right - (fontSize / 2);
titleY = top + ((bottom - top) / 2);
maxWidth = bottom - top;
rotation = Math.PI * (opts.position === 'left' ? -0.5 : 0.5);
}
@ -178,7 +181,7 @@ module.exports = function(Chart) {
ctx.rotate(rotation);
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(opts.text, 0, 0);
ctx.fillText(opts.text, 0, 0, maxWidth);
ctx.restore();
}
}