简体   繁体   中英

What is the best way to draw text on an HTML canvas element?

The canvas element unfortunately doesn't handle text well. There are a bunch of approaches (see eg http://canvaspaint.org/blog/2006/12/rendering-text/ ), but they mostly seem like hacks. What can I do that is cross-platform and gives me the most flexibility to make my fonts like how I want?

Have you looked at typeface.js, http://typeface.neocracy.org . I hear it's pretty solid for writing text. Here's from their site:

"typeface.js uses browsers' vector drawing capabilites to draw text in HTML documents. For a good while, browsers have had support for vector drawing -- Firefox, Safari, and Opera support the <canvas> element (as well as SVG), and IE supports VML.

The typeface.js project has two components: the perl module for converting fonts, and the javascript library for drawing in the browser. The perl module extracts glyph outline information from truetype fonts and writes that data in JSON format. The javascript library then traverses the HTML document and renders text using <canvas> or VML to draw the glyphs.

In browsers that support <canvas> the text is selectable, but you have to have faith. As you select there's no feedback, no highlighting to let you know that it's working. Future work will aim to implement better, cross-browser support for selecting text with highlighting." (quote from http://typeface.neocracy.org/usage.html )

If you want to use the HTML5 text methods, you should try this library : http://code.google.com/p/canvas-text/ I'm the main developer, so I can help, and make changes really quickly.

The demos are here : http://canvas-text.googlecode.com/svn/trunk/examples/index.html

It is still in alpha stage, so any bug report and feedback are welcome ! :)

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