2

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?

cnd
  • 32,616
  • 62
  • 183
  • 313
Martin Wiegel
  • 29
  • 1
  • 2
  • Do you need to write it on the `canvas`? Are you going to manipulate it in some way? Otherwise you could just create a `div` with the text in it and position it in front of your canvas. – robertc Apr 20 '12 at 11:58
  • Yes i need to put in in the canvas. I want to animate it with some other elements. – Martin Wiegel Apr 20 '12 at 12:22
  • Yes i need font. It is the output from an flex html textbox. – Martin Wiegel Apr 20 '12 at 12:24
  • **See Also**: [HTML5 Canvas API - formatting individual words with italics](https://stackoverflow.com/q/24163211/1366033) – KyleMit Nov 19 '20 at 19:55

2 Answers2

2

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)
    
KyleMit
  • 30,350
  • 66
  • 462
  • 664
Jocelyn LECOMTE
  • 875
  • 1
  • 7
  • 15
0

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.

jing3142
  • 1,821
  • 1
  • 11
  • 16