HTML5 canvas ctx.fillText won't do line breaks?

前端 未结 17 1082
甜味超标
甜味超标 2020-11-28 01:37

I can\'t seem to be able to add text to a canvas if the text includes \"\\n\". I mean, the line breaks do not show/work.

ctxPaint.fillText(\"s  ome \\n \\\\n         


        
17条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-28 02:30

    Here's a version of Colin's wrapText() that also supports vertically centered text with context.textBaseline = 'middle':

    var wrapText = function (context, text, x, y, maxWidth, lineHeight) {
        var paragraphs = text.split("\n");
        var textLines = [];
    
        // Loop through paragraphs
        for (var p = 0; p < paragraphs.length; p++) {
            var line = "";
            var words = paragraphs[p].split(" ");
            // Loop through words
            for (var w = 0; w < words.length; w++) {
                var testLine = line + words[w] + " ";
                var metrics = context.measureText(testLine);
                var testWidth = metrics.width;
                // Make a line break if line is too long
                if (testWidth > maxWidth) {
                    textLines.push(line.trim());
                    line = words[w] + " ";
                }
                else {
                    line = testLine;
                }
            }
            textLines.push(line.trim());
        }
    
        // Move text up if centered vertically
        if (context.textBaseline === 'middle')
            y = y - ((textLines.length-1) * lineHeight) / 2;
    
        // Render text on canvas
        for (var tl = 0; tl < textLines.length; tl++) {
            context.fillText(textLines[tl], x, y);
            y += lineHeight;
        }
    };
    

提交回复
热议问题