简体   繁体   English

如何在html5 canvas filltext()方法中呈现html标签?

[英]how can render html tags in html5 canvas filltext() method?

how can render HTML tags in html5 canvas filltext() method? 如何在html5 canvas filltext()方法中呈现HTML标签?

for example here is the rest of the code: 例如,下面是代码的其余部分:

context.fillText(
        "label: " + "hossein" + "<br/>" + "id: " + "52" + "<br/>",
        Math.round(node[prefix + 'x'] + size + 10),
            Math.round(node[prefix + 'y'] - 60)
);

is correct the <br> html tag that I use in code? 我在代码中使用的<br> html标记正确吗? does it work correct? 它工作正常吗?

if not how must I use that? 如果不是,我该怎么用?

The fillText() method can only take plain text and doesn't parse any tags within it. fillText()方法只能接受纯文本,而不能解析其中的任何标签。 If your text is as simple as here you can however make your own parser. 如果您的文本如此简单,则可以创建自己的解析器。

function myFillText(txt, x, y) {

    // get a pseudo height for the font
    var fontParts = context.font.split(' '),
        fontHeight = parseInt(fontParts.length === 2 ? fontParts[0] : fontParts[1], 10),
        // split the text based on HTML5 line-breaks
        txtParts = txt.split('<br>'),
        i = 0;

    // iteate parts and increase line position for each line
    for(; i < txtParts.length; i++) {
        context.fillText(txtParts[i], x, y + i * fontHeight);
    }
}

Now simply use this instead: 现在,只需使用以下代码即可:

myFillText("label: " + "hossein" + "<br>" + "id: " + "52" + "<br>",
           Math.round(node[prefix + 'x'] + size + 10),
           Math.round(node[prefix + 'y'] - 60));

Online demo 在线演示

PS: if you're using HTML5 then you can use <br> without the back-slash. PS:如果您使用的是HTML5,则可以使用<br>而不使用反斜杠。 The back-slash is for XHTML - or modify the parser to support the other form. 反斜杠用于XHTML-或修改解析器以支持其他形式。

You can't use html tags inside Canvas. 您不能在Canvas中使用html标签。 Canvas has its own set of drawing commands. 画布具有其自己的一组绘制命令。

As you've discovered, one of those drawing commands is fillText. 正如您所发现的那样,这些绘制命令之一是fillText。

If you want multi-lines of canvas text, you must do multiple fillText commands and increase the y-coordinate of each succeeding fillText. 如果要多行画布文本,则必须执行多个fillText命令,并增加每个后续fillText的y坐标。

var x = Math.round(node[prefix + 'x'] + size + 10);

var y = Math.round(node[prefix + 'y'] - 60);

var myLineHeight=16  // space between lines of text

fillText("label: "+"hossein", x,y);

fillText("id: "+"52", x,y+myLineHeight);

fillText("Other stuff", x,y+myLineHeight*2);

fillText("Even more stuff", x,y+myLineHeight*3);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM