1

I have the following simple html:

<h1><i>This is a test</i> <span class="wysiwyg-color-red">Hello world</span></h1>

I would like to create a text html to canvas converter using a set of basic styles and strokeText html5 canvas api method.

It would be useful to get a 'tree' of node values and the list of html html elements.

{ 
  "This is a test": ["i", "h1"],
  "Hello world": ["span class="wysiwyg-color-red", "h1"]
} 

From that I would be able to generate appropriate canvas text styles.

Answer:

http://jsfiddle.net/AUTJs/4/

1
  • Do you have control over the HTML code above? When you do, it would be helpful to add id properties to the HTML tags you need in your javascript code, because it allows you to access them easily with document.getElementById(); Commented Apr 16, 2013 at 10:57

2 Answers 2

4

The best way to do it is to put it on the DOM in a hidden container, let the browser reconcile the errors in the html (unclosed tags and so on) and then simply iterate the elements in that container. Best use jQuery for that. For each node you get, you can ask jquery to give you the tagname, the classnames, the style attributes or whatever you need, the text inside, width and height and all the things you will need. Draw it to the canvas and then recourse with the child nodes of this element, and so on until it's done. HTML2Canvas library does the same thing. It relies on the browser to tell it font sizes and colors and z-indexes and node orders and all that.

Even for a simple html like yours, doing it this way will save you a lot of time and trouble.

Sign up to request clarification or add additional context in comments.

Comments

1

Maybe you just need something that can render HTML on the canvas element? So that "screenshot" of the page would be painted on the canvas.

Check out http://html2canvas.hertzen.com/ and http://experiments.hertzen.com/jsfeedback/.

1 Comment

svg Rasterization has some issues with security sandbox, i would rather try something with text canvas API

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.