vrmkfg
Last Updated: February 25, 2016
·
313
· mkommar

Wrap text and left align in canvas

I needed to put in labels in a canvas element (rendered by chart js), I put this bit of code in there to add the labels so that it word wrapped, added a legend color, and adding padding.

_wrapText = function wrapText(context, text, x, y, maxWidth, lineHeight) {
            var words = text.split(' ');
            var currentXLocation = x;
            i = 0;
            for(var n = 0; n < words.length; n++) {
                var currentWord = words[n] + ' ';
                var metrics = context.measureText(currentWord);
                wordWidth = metrics.width;

                if(n === 0) {
                    prevWordWidth = 0;
                    currentXLocation = x;
                } else {
                    metrics = context.measureText(words[n-1]);
                    prevWordWidth = metrics.width;
                    currentXLocation += 50 + prevWordWidth;
                }

                if((currentXLocation + wordWidth + 50) > maxWidth) {
                    y += lineHeight;
                    currentXLocation = x;
                }
                var rgb = 'rgb(' + graphColors[i]['r'] + ', ' + graphColors[i]['g'] + ', ' + graphColors[i]['b'] + ')';
                context.fillStyle = rgb;
                context.fillRect(currentXLocation, y - (lineHeight/2),20,20);
                context.fillStyle = "#666";
                context.fillText(currentWord, currentXLocation + 30, y);
                i++;
                if(i >= graphColors.length) {
                    i = 0;
                }
            }
        }