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?

4
  • 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. Commented Apr 20, 2012 at 11:58
  • Yes i need to put in in the canvas. I want to animate it with some other elements. Commented Apr 20, 2012 at 12:22
  • Yes i need font. It is the output from an flex html textbox. Commented Apr 20, 2012 at 12:24
  • See Also: HTML5 Canvas API - formatting individual words with italics Commented Nov 19, 2020 at 19:55

2 Answers 2

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)
    
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.