简体   繁体   中英

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

how can render HTML tags in html5 canvas filltext() method?

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? 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. 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. The back-slash is for XHTML - or modify the parser to support the other form.

You can't use html tags inside Canvas. Canvas has its own set of drawing commands.

As you've discovered, one of those drawing commands is fillText.

If you want multi-lines of canvas text, you must do multiple fillText commands and increase the y-coordinate of each succeeding fillText.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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