Last Updated: February 25, 2016
·
819
· 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;
                }
            }
        }

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside