{"componentChunkName":"component---src-templates-post-tsx","path":"/draw-text-with-webgl","result":{"data":{"markdownRemark":{"html":"<p>There are two main ways to render text with WebGL.</p>\n<h2>Character Bitmap</h2>\n<p>This method is quite straightforward. First, draw all characters you need on a canvas (of course in 2D context). Then use the image as a texture map. But if you’re going to render text under many font sizes. You need to store many character bitmaps of different font sizes. I found <a href=\"https://github.com/hughsk/font-atlas\" target=\"_blank\" rel=\"noopener noreferrer\">a package</a> doing this job.</p>\n<h2>Vectorized Text</h2>\n<p>The second way is to convert outline (usually Bézier curves) of characters into triangle mesh. Then draw the mesh by WebGL. I also found <a href=\"https://github.com/mikolalysenko/vectorize-text\" target=\"_blank\" rel=\"noopener noreferrer\">a package called <code class=\"language-text\">vectorize-text</code></a> doing this job. It’s also based on canvas. I think its implementation is a little bit hack. First, it draw your text with your options on an invisible large canvas. Second, it fetch all pixels and use a package called surface-nets to find all contours and simplify it by simplify-planar-graph. Finally, it cleans all planar straight line graphs by the help of <a href=\"https://github.com/mikolalysenko/clean-pslg\" target=\"_blank\" rel=\"noopener noreferrer\">clean-pslg</a>. Because we want triangle meshes. It uses <a href=\"https://github.com/mikolalysenko/cdt2d&#x27;\" target=\"_blank\" rel=\"noopener noreferrer\">cdt2d</a> to convert contours to meshes.</p>\n<p>It seems that the whole process is really costly, especially when you want to vectorize a large amount of texts. I will do a performance test later on.</p>\n<h2>An OpenType Way</h2>\n<p>Last night, I tried a new way with OpenType. The main idea is to get glyph outlines directly from font files. Then convert them into triangle meshes. I think it can be the most accurate and fast way to draw text because the outlines are rasterized only once. The good news is that <a href=\"https://github.com/opentypejs/opentype.js\" target=\"_blank\" rel=\"noopener noreferrer\">opentype.js</a> has already taken kerning, OpenType features and hinting into account. But the bad news is you have to handle position (such as baseline, anchor) or even word wrap by yourself.</p>\n<h2>Conclusion</h2>\n<p>Well, no conclusion is drawn in this post. This post is a like a summary of my adventures. But I will finish it in next few days.</p>","frontmatter":{"title":"Draw Text with WebGL","date":"January 17, 2020","tags":["webgl","text-rendering"],"language":"en"}},"site":{"siteMetadata":{"title":"Luyu Cheng"}}},"pageContext":{"id":"fc591339-90f9-5e23-8f9f-9b02dfb89a65"}},"staticQueryHashes":["3649515864","63159454","684267432"]}