SVG & colors in OpenType fonts

Sample of a colorfont

Prolog

Until recently having more than one color in a glyph of a vector font was technically not possible. Getting a polychrome letter required multiplying the content for every color. Like it happened with many other techniques before, it took some time for digital type to overcome the constraints of the old technique. When printing with wood or lead type the limitation to one color per glyph is inherent (if you don’t count random gradients). More than one color per letter required separate fonts for the differently colored parts and a new print run for every color. This has been done beautifully and pictures of some magnificent examples are available online. Using overprinting the impression of three colors can be achieved with just two colors.

Overprinting colors
Simulation of two overprinting colors resulting in a third.

Digital font formats kept the limitation to one ‘surface’ per glyph. There can be several outlines in a glyph but when the font is used to set type the assigned color applies to all outlines. Analog to letterpress the content needs to be doubled and superimposed to have more than one color per glyph. Multiplying does not sound like an elegant solution and it is a constant source of errors.

It took some emojis until the demand for multi-colored fonts was big enough to develop additional tables to store this information within OpenType fonts. As of this writing there are several different ways to implement this. Adam Twardoch compares all proposed solutions in great detail on the FontLab blog.

To me the Adobe/Mozilla way looks the most intriguing.

Upon its proposal it was discussed by a W3C community group and published as a stable document. The basic idea is to store the colored glyphs as svgs in the OpenType font. Of course this depends on the complexity of your typeface but svgs should usually result in a smaller file size than pngs. With the development of high resolution screens vectors also seem to be a better solution than pixels. The possibility to animate the svgs is an interesting addition and will surely be used in interesting (and very annoying) ways. BLING BLING.

Technique

I am not a font technician or a web developer just very curious about this new developments. There might be other ways but this is how I managed to build colorful OpenType fonts.

In order to make your own you will need a font editor. There are several options like RoboFont and Glyphs (both Mac only), FontLab and the free FontForge. RoboFont is the editor of my choice, since it is highly customizable and you can build your own extensions with python. In a new font I added as many new layers as the amount of colors I wanted to have in the final font. Either draw in the separate layers right away or just copy the outlines into the respective layer after you’ve drawn them in the foreground layer. With the very handy Layer Preview extension you can preview all Layers overlapping. You can also just increase the size of the thumbnails in the font window. At some point they will show all layers. Adjust the colors to your liking in the Inspector since they are used for the preview.

RoboFont Inspector
Define the colors you want to see in the Layer Preview
A separated letter
Layer preview
The outlines of the separate layers and their combination

When you are done drawing your outlines you will need to safe a ufo for every layer / color. I used a little python script to safe them in the same place as the main file:

f = CurrentFont()
path = f.path

for layer in f.layerOrder:
newFont = RFont()

for g in f:
    orig = g.getLayer(layer)
    newFont.newGlyph(g.name)
    newFont[g.name].appendGlyph(orig)
    newFont[g.name].width = orig.width
    newFont[g.name].update()

newFont.info.familyName = f.info.familyName
newFont.info.styleName = layer
newFont.save(destDir = path[:-4] +"_%s" % layer +".ufo")
newFont.close()

print "Done Splitting"

Once I had all my separate ufos I loaded them into TransType from FontLab. Just drop your ufos in the main window and select the ones you want to combine. In the Effect menu click ‘Overlay Fonts …’. You get a preview window where you can assign a rgba value for each ufo and then hit OK. Select the newly added font in the collection and export it as OpenType (ttf). You will get a folder with all colorfont versions.

TransType
The preview of your colorfont in TransType.

RoboChrome

In case you don’t want to use TransType you might have a look at the very powerful RoboFont extension by Jens Kutílek called RoboChrome. You will need a separate version of your base-glyph for every color, which can also be done with a scipt if you have all of your outlines in layers.

f = CurrentFont()
selection = f.selection

for l, layer in enumerate(f.layerOrder):
for g in selection:
    char = f[g]
    name = g + ".layer%d" % l
    f.newGlyph(name)
    f[name].width = f[g].width
    l_glyph = f[g].getLayer(layer)
    f[name].appendGlyph(l_glyph)
    f[name].mark = (.2, .2, .2, .2)

print "Done with the Devision"
For RoboChrome you will need to split your glyph into several.

Fonttools

You can also modify the svg table of a compiled font or insert your own if it does not have any yet. To do so I used the very helpful fonttools by Just van Rossum. Just generate a otf or ttf with the font editor of your choice. Open the Terminal and type ttx if you are on Mac OS and have fonttools installed. Drop the font file in the Terminal window and hit return. Fonttools will convert your font into an xml (YourFontName.ttx) in the same folder. This file can then be opened, modified and recompiled into a otf or ttf.

This can be quite helpful to streamline the svg compiled by a program and therefore reduce the file size. I rewrote the svg of a 1.6mb font to get it down to 980kb. Using it as a webfont that makes quite a difference. If you want to add your own svg table and font that does not have any yet you might read a bit about the required header information. The endGlyphID and startGlyphID for the glyph you want to supply with svg data can be found in the <GlyphOrder> Table.



    
    <!-- here goes your svg -->
    ]]&gt;
</svgDoc>
<svgDoc endGlyphID="19" startGlyphID="19">...</svgDoc>
<svgDoc endGlyphID="20" startGlyphID="20">...</svgDoc>
...
<colorPalettes></colorPalettes>
</svg></pre>
<p>
One thing to keep in mind is the two different coordinate systems.  Contrary to a digital font svg has a y-down axis. So you either have to draw in the negative space or you draw reversed and then mirror everything with: </p>
<pre lang="css">transform="scale(1,-1)"</pre>
<figure>
    <a href="http://blog.mozilla.org/hacks/files/2014/10/svg-coordinates.png"><img src="http://blog.mozilla.org/hacks/files/2014/10/svg-coordinates-500.png" alt="Y-axis comparison"></a><figcaption>While typefaces usually have a y-up axis SVG uses y-down.</figcaption></figure>
<h2>Animation</h2>
<p>
Now if you really want to pimp your fonts you should add some unnecessary animation to annoy everybody.  Just insert it between the opening and closing tags of whatever you want to modify. Here is an example of a circle changing its fill-opacity from zero to 100% over a duration of 500ms in a loop.  </p>
<pre lang="xml"><circle>
<animate    attributeName="fill-opacity"
            begin="0"
            dur="500ms"
            from="0"
            to="1"
            repeatCount="indefinite"/>
</circle></pre>
<figure>
<img src="http://colorfonts.langustefonts.com/imgs/unicorn3.svg" alt=""><br />
</figure>
<h2>Implementation</h2>
<p>Technically these fonts should work in any application that works with otfs or ttfs. But as of this writing only Firefox shows the svg. If the rendering is not supported the application will just use the regular glyph outlines as a fallback.  So if you have your font(s) ready it’s time to write some css and html to test and display them on a website.</p>
<p></p>
<p>The @font-face</p>
<pre lang="css">@font-face {
font-family: "Colors-Yes"; /* reference name */
src: url('./fonts/Name_of_your_font.ttf');
font-weight: 400; /* or whatever applies */
font-style: normal; /* or whatever applies */
text-rendering: optimizeLegibility; /* maybe */
}</pre>
<p>The basic css</p>
<pre lang="css">.color_font { font-family: "Colors-Yes"; }</pre>
<p>The HTML</p>
<pre lang="xml"><p class="color_font">Shiny polychromatic text</p></pre>
<h2>Restrictions</h2>
<p>As of this writing (October 2014) the format is supported by Firefox (26+) only. Since this was initiated by Adobe and Mozilla there might be a broader support in the future. </p>
<p>
While using svg has the advantage of reasonably small files and the content does not have to be multiplied it brings one major drawback.  Since the colors are ‘hard-coded’ into the font there is no possibility to access them with css.  Hopefully this might change with the implementation of a &lt;COLR/CPAL&gt; table. </p>
<p>There is a <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=1058634" target="_blank">bug</a> that keeps animations from being played in Firefox 32.  While animations are rendered in the current version (33) this might change for obvious reasons. </p>
<p>Depending how you establish your svg table it might blow up and result in fairly big files. Be aware of that in case you use them to render the most crucial content of your websites.</p>
<h2>Examples</h2>
<ul>
<li><a href="http://colorfonts.langustefonts.com/index.html" target="_blank">Carving typeface</a></li>
<li><a href="http://colorfonts.langustefonts.com/flags.html" target="_blank">International maritime signal flags</a> The flag alphabet of the ICS</li>
<li><a href="http://colorfonts.langustefonts.com/disco.html" target="_blank">Sparkle Motion</a> Be warned! A hefty 980kb font with lots of animation. </li>
<li><a href="http://colorfonts.langustefonts.com/drunk_disco.html" target="_blank">Bubbles gone wrong</a> do not confuse $1 and $2 in your grep. </li>
</ul>
<h2>Links, Credits &#038; Thanks</h2>
<ul>
<li>The <a href="http://www.w3.org/2013/10/SVG_in_OpenType/" target="_blank"> Specifications of svg glyphs in OpenType</a> on <a href="http://www.w3.org/" target="_blank">w3.org</a></li>
<li>The <a href="http://unifiedfontobject.org/" target="_blank">ufo</a> format by Tal Leming, Just van Rossum and Erik van Blokland</li>
<li><a href="http://robofont.com/" target="_blank">Robofont</a> by Frederik Berlaen</li>
<li><a href="https://github.com/typemytype/RoboFontExtensions/tree/master/LayerPreview" target="_blank">Layer preview</a> for Robofont by Frederik Berlaen</li>
<li><a href="https://github.com/fontfont/RoboChrome" target="_blank">RoboChrome</a> for Robofont by Jens Kutílek</li>
<li><a href="http://www.fontlab.com/font-converter/transtype/" target="_blank">TransType</a> by <a href="http://www.fontlab.com/" target="_blank">FontLab</a></li>
<li><a href="http://sourceforge.net/projects/fonttools/" target="_blank">fonttools</a> by Just van Rossum and <a href="https://github.com/behdad/fonttools/" target="_blank">a fork on github</a></li>
<li><a href="https://archive.org/stream/ldpd_10147342_000#page/n0/mode/thumb" target="_blank">Polychromatic type specimen</a> on archive.org</li>
<li><a href="http://people.mozilla.org/~jkew/opentype-svg/soccer.html" target="_blank">An animated sample from mozilla</a></li>
<li>Syntax highlighting done with <a href="http://prismjs.com/" target="_blank">prism</a>.</li>
<li><a href="https://symbolset.com" target="_blank">Symbolset</a> has a similar <a href="http://blog.symbolset.com/making-ss-emoji" target="_blank">Tutorial</a></li>
</ul>
<p></p>
<p>Thanks Erik, Frederik, Just and Tal for making great tools! </p>
    <section class="about">
                                <h2 class="about__header">About
                          <a class="url" href="http://langustefonts.com" rel="external me">
                Johannes Lang              </a>
                      </h3>
                      <p>I am a graphic and type designer working in Vienna (Austria). I am also part-time teaching typography at the university of applied arts Vienna. I like paper objects and riding my bicycle.</p>
                    <ul class="author-meta fa-ul"><li><i class="fa-li fa fa-globe"></i><a href="http://langustefonts.com" class="website" rel="me">langustefonts.com</a></li><li><i class="fa-li fa fa-twitter"></i><a href="http://twitter.com/langustefonts" class="twitter" rel="me">@langustefonts</a></li></ul>            <p><a class="url" href="https://hacks.mozilla.org/author/johanneslang/">More articles by Johannes Lang&hellip;</a></p>
                  <h2 class="about__header">About
                          <a class="url" href="http://robertnyman.com" rel="external me">
                Robert Nyman [Editor emeritus]              </a>
                      </h3>
                      <p>Technical Evangelist &amp; Editor of Mozilla Hacks. Gives talks &amp; blogs about HTML5, JavaScript &amp; the Open Web. Robert is a strong believer in HTML5 and the Open Web and  has been working since 1999 with Front End development for the web - in Sweden and in New York City.

He regularly also blogs at <a href="http://robertnyman.com">http://robertnyman.com</a> and loves to travel and meet people.</p>
                    <ul class="author-meta fa-ul"><li><i class="fa-li fa fa-globe"></i><a href="http://robertnyman.com" class="website" rel="me">robertnyman.com</a></li><li><i class="fa-li fa fa-twitter"></i><a href="http://twitter.com/robertnyman" class="twitter" rel="me">@robertnyman</a></li><li><i class="fa-li fa fa-google-plus"></i><a href="https://plus.google.com/u/0/118100898483063383963" class="gplus" rel="me">Google+</a></li></ul>            <p><a class="url" href="https://hacks.mozilla.org/author/robertnyman/">More articles by Robert Nyman [Editor emeritus]&hellip;</a></p>
                  </section>
  </article>
  <section class="promo">
    <form id="newsletterForm" name="newsletter-form" class="newsletter block block--1 block--polite" action="https://www.mozilla.org/en-US/newsletter/" method="post">
  <h2 class="heading">Discover great resources for web development</h2>
  <p class="newsletter__description">Sign up for the Mozilla Developer Newsletter:</p>
  <input id="fmt" name="fmt" value="H" type="hidden">
  <input id="newsletterNewslettersInput" name="newsletters" value="app-dev" type="hidden">

  <div id="newsletterErrors" class="newsletter__errors"></div>

  <div id="newsletterEmail" class="form__row">
    <label for="newsletterEmailInput" class="offscreen">E-mail</label>
    <input id="newsletterEmailInput" name="email" class="newsletter__input" required="" placeholder="you@example.com" size="30" type="email">
  </div>

  <div id="newsletterPrivacy" class="form__row form__fineprint">
    <input id="newsletterPrivacyInput" name="privacy" required="" type="checkbox">
    <label for="newsletterPrivacyInput">
      I'm okay with Mozilla handling my info as explained in this <a href="https://www.mozilla.org/privacy/">Privacy Policy</a>.
    </label>
  </div>
  <button id="newsletter-submit" type="submit" class="button positive">Sign up now</button>
</form>
<div id="newsletterThanks" class="newsletter newsletter--thanks block block--1 block--polite hidden">
  <h2 class="heading">Thanks! Please check your inbox to confirm your subscription.</h2>
  <p>If you haven’t previously confirmed a subscription to a Mozilla-related newsletter you may have to do so. Please check your inbox or your spam filter for an email from us.
  </p>
</div>
  </section>
  

</main><!-- /#content-main -->

  

    <footer class="footer section section--fullwidth">
      <div class="row">
        <p class="block block--1">
          Except where otherwise noted, content on this site is licensed
          under the
          <a href="https://creativecommons.org/licenses/by-sa/3.0/" rel="license external">Creative Commons Attribution Share-Alike License v3.0</a>
          or any later version.
        </p>
        <img class="footer__logo" alt="the Mozilla dino logo" src="https://2r4s9p1yi1fa2jd7j43zph8r-wpengine.netdna-ssl.com/wp-content/themes/Hax/img/dino.svg">
      </div>
    </footer>
  </div>
  <link rel='stylesheet' id='hljstheme-css'  href='https://2r4s9p1yi1fa2jd7j43zph8r-wpengine.netdna-ssl.com/wp-content/plugins/wp-code-highlightjs/styles/solarized-light.css?ver=0.6.2' type='text/css' media='all' />
<script type='text/javascript' src='https://2r4s9p1yi1fa2jd7j43zph8r-wpengine.netdna-ssl.com/wp-includes/js/wp-embed.min.js?ver=5.4.2'></script>
<script type='text/javascript' src='https://2r4s9p1yi1fa2jd7j43zph8r-wpengine.netdna-ssl.com/wp-content/plugins/wp-code-highlightjs/highlight.common.pack.js?ver=0.6.2'></script>
<script type='text/javascript' src='https://2r4s9p1yi1fa2jd7j43zph8r-wpengine.netdna-ssl.com/wp-content/plugins/wp-code-highlightjs/highlight.custom.pack.js?ver=0.6.2'></script>
    <style>pre.hljs {padding: 5px;}
pre.hljs code {}</style>
    <script type="text/javascript">
    (function($, window) {
        var init_fn_flag = false;
        var init_fn = (function() {
            if (init_fn_flag)
                return;
            init_fn_flag = true;
             hljs.configure({"tabReplace":"    "});
            $('pre code').each(function(i, block) {
                hljs.highlightBlock(block);
            });
        });
        $(document).ready(init_fn);
        $(window).on("load", init_fn);
    })(jQuery, window);
    </script>
  <script>
    // External links should open in a new tab.
    (function () {
      var postLinks = document.querySelectorAll('#content-main a');

      var origin = location.origin;

      for (var i = 0; i < postLinks.length; i++) {
        var link = postLinks[i];
        if (link.origin !== origin && !link.getAttribute('target')) {
          link.setAttribute('target', '_blank');
        }
      }
    })();

    window.addEventListener('load', function () {
      if (document.querySelector('#newsletterForm')) {
        var script = document.createElement('script');
        var path = document.head.getAttribute('data-template-path');
        script.setAttribute('src', path + '/js/newsletter.js');
        document.head.appendChild(script);
      }
    });
  </script>
</body>
</html>