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

前端 未结 17 1041
甜味超标
甜味超标 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:27

    Using javascript I developed a solution. It isn't beautiful but it worked for me:


    function drawMultilineText(){
    
        // set context and formatting   
        var context = document.getElementById("canvas").getContext('2d');
        context.font = fontStyleStr;
        context.textAlign = "center";
        context.textBaseline = "top";
        context.fillStyle = "#000000";
    
        // prepare textarea value to be drawn as multiline text.
        var textval = document.getElementByID("textarea").value;
        var textvalArr = toMultiLine(textval);
        var linespacing = 25;
        var startX = 0;
        var startY = 0;
    
        // draw each line on canvas. 
        for(var i = 0; i < textvalArr.length; i++){
            context.fillText(textvalArr[i], x, y);
            y += linespacing;
        }
    }
    
    // Creates an array where the 
    tag splits the values. function toMultiLine(text){ var textArr = new Array(); text = text.replace(/\n\r?/g, '
    '); textArr = text.split("
    "); return textArr; }

    Hope that helps!

提交回复
热议问题