Martin Wiegel
Martin Wiegel

Reputation: 29

Add Html Text to Html5 Canvas

I got from a different Application a html formatted Text from user input. (With font b br ul and so on, different fonts and colors in one fragment )

I would like to write this on a canvas.

like context.write("<b>Hello</b> World <font...>more text </font>");

how can i do this?

Upvotes: 2

Views: 2921

Answers (2)

Jocelyn LECOMTE
Jocelyn LECOMTE

Reputation: 885

First, you'll have to make available to the canvas all the fonts you are using @font-face if needed.

Then you'll have to describe all the operations needed to draw the text, remember canvas is just a drawing surface. You'll have to iterate over these steps:

  1. Specify the font to be used: (same syntax as the CSS font property)

    context.font = "12px Arial bold"
    
  2. Measure the string that will be drawn to know where to place the next one:

    context.measureText(txt).width
    
  3. Draw your text (fill or stroke):

    context.fillText(txt, x, y)
    

Upvotes: 2

jing3142
jing3142

Reputation: 1871

This should help

https://developer.mozilla.org/en/Drawing_text_using_a_canvas

Though you would need to read the formats from the html and re-apply using this method.

Upvotes: 0

Related Questions