Chrome OffscreenCanvas自定义字体

时间:2018-12-17 01:46:59

标签: html5 canvas

我正在使用Chrome 69中发布的新版OffscreenCanvas,似乎无法呈现自定义加载的字体,而这种字体可以很好地呈现给普通画布。

是否有一种技巧可以使工作程序中提供自定义字体,以便OffscreenCanvas可以访问它?

1 个答案:

答案 0 :(得分:0)

您应该能够在Worker中使用FontFaceFontFaceSetCSS Font Loading API接口。

主要区别在于,FontFaceSet不是通过document.fonts访问,而是直接存储为self.fonts

const worker = new Worker(generateURL(worker_script));
worker.onmessage = e => {
  const img = e.data;
  if(typeof img === 'string') {
    console.error(img);
  }
  else
    renderer.getContext('2d').drawImage(img, 0,0);
};

function generateURL(el) {
  const blob = new Blob([el.textContent]);
  return URL.createObjectURL(blob);
}
<script type="worker-script" id="worker_script">
  if(self.FontFace) {
    // first declare our font-face
    const fontFace = new FontFace(
      'Shadows Into Light',
      "local('Shadows Into Light'), local('ShadowsIntoLight'), url(https://fonts.gstatic.com/s/shadowsintolight/v7/UqyNK9UOIntux_czAvDQx_ZcHqZXBNQzdcD55TecYQ.woff2) format('woff2')"
    );
    // add it to the list of fonts our worker supports
    self.fonts.add(fontFace);
    // load the font
    fontFace.load()
    .then(()=> {
      // font loaded
      if(!self.OffscreenCanvas) {
        postMessage("Your browser doesn't support OffscreeenCanvas yet");
        return;
      }
      const canvas = new OffscreenCanvas(300, 150);
      const ctx = canvas.getContext('2d');
      if(!ctx) {
        postMessage("Your browser doesn't support the 2d context yet...");
        return;
      }
      ctx.font = '50px "Shadows Into Light"';
      ctx.fillText('Hello world', 10, 50);
      const img = canvas.transferToImageBitmap();
      self.postMessage(img, [img]);
    });
  } else {
    postMessage("Your browser doesn't support the FontFace API from WebWorkers yet");
  }
  
</script>
<canvas id="renderer"></canvas>