Text wrap in a element

后端 未结 10 2345
[愿得一人]
[愿得一人] 2020-11-29 02:43

I am trying to add text on an image using the element. First the image is drawn and on the image the text is drawn. So far so good.

But w

10条回答
  •  萌比男神i
    2020-11-29 02:44

    From the script here: http://www.html5canvastutorials.com/tutorials/html5-canvas-wrap-text-tutorial/

    I've extended to include paragraph support. Use \n for new line.

    function wrapText(context, text, x, y, line_width, line_height)
    {
        var line = '';
        var paragraphs = text.split('\n');
        for (var i = 0; i < paragraphs.length; i++)
        {
            var words = paragraphs[i].split(' ');
            for (var n = 0; n < words.length; n++)
            {
                var testLine = line + words[n] + ' ';
                var metrics = context.measureText(testLine);
                var testWidth = metrics.width;
                if (testWidth > line_width && n > 0)
                {
                    context.fillText(line, x, y);
                    line = words[n] + ' ';
                    y += line_height;
                }
                else
                {
                    line = testLine;
                }
            }
            context.fillText(line, x, y);
            y += line_height;
            line = '';
        }
    }
    

    Text can be formatted like so:

    var text = 
    [
        "Paragraph 1.",
        "\n\n",
        "Paragraph 2."
    ].join("");
    

    Use:

    wrapText(context, text, x, y, line_width, line_height);
    

    in place of

    context.fillText(text, x, y);
    

提交回复
热议问题