Font Loading for Canvas

by Martin

HTML

<script src="https://ajax.googleapis.com/ajax/libs/webfont/1.6.26/webfont.js"></script>
<canvas id="c" width="400" height="130">
  <p>No canvas.</p>
</canvas>

CSS

body {
  background: #cccccc;
}

#c {
  display: block;
  margin: 10px auto;
  background: white;
}

@font-face {
  font-family: 'MyCustomFamilyWithLocal';
  font-style: normal;
  font-weight: 400;
  src: local('MyCustomFamilyWithLocal'), url(https://fonts.gstatic.com/s/indieflower/v8/10JVD_humAd5zP2yrFqw6hampu5_7CjHW5spxoeN3Vs.woff2) format('woff2');
}

@font-face {
  font-family: 'MyCustomFamily';
  font-style: normal;
  font-weight: 400;
  src:  url(https://fonts.gstatic.com/s/gloriahallelujah/v8/CA1k7SlXcY5kvI81M_R28YGdvEu4SOXaLqFXyFUihk4.woff2) format('woff2');
}

JavaScript

WebFont.load({
  custom: {
    families: ['MyCustomFamily', 'MyCustomFamilyWithLocal']
  },
  active: function() {
    var canvas = document.getElementsByTagName("canvas")[0];
    var ctx = canvas.getContext('2d');

    ctx.font = "40px 'MyCustomFamilyWithLocal'";
    ctx.fillText("With Local Src", 10, 50);
    
    ctx.font = "40px 'MyCustomFamily'";
    ctx.fillText("No Local Src", 10, 100);
  },
  fontactive: function(fam, fvd) {
    console.log("fontactive", fam, fvd);
  },
  fontinactive: function(fam, fvd) {
    console.log("fontinactive", fam, fvd);
  }
});