我如何“写作"上下文画布中的图标?

2022-01-17 00:00:00 canvas javascript html css html5-canvas

这是我的字体:
@font-face {font-family: "myicon";/*...*/}
我的图标在 css 中的内容是:
content: "e000";
我的 Js 代码:
ctx.font = '13.5pt myicon';ctx.fillText("ue000",90, 101);//不工作

你能解释一下问题出在哪里吗?为什么不打印图标?(对不起我的英语不好)

This is my type font:
@font-face {font-family: "myicon";/*...*/}
And the content for my icon in css is:
content: "e000";
My Js code:
ctx.font = '13.5pt myicon'; ctx.fillText("ue000",90, 101); //not working

can you explain me where is the problem ? why not print the icon ? (Sorry for my bad english)

推荐答案

虽然你可以使用 markE 提到的脚本,但你也可以只粘贴一个等待字体加载的小片段.

Although you can use script such as the one markE mentions, you can also just paste in a small snippet that waits for the font to load.

脚本将通过以下方式进行测试:

The script will test by doing:

  • 创建一个内部画布,为其绘制默认字体并存储其像素
  • 尝试每隔一段时间设置你想要的字体,绘制它并提取它的像素
  • 如果像素级没有差异,再等等
  • 在第一个像素差异时,我们加载了一个新字体(大概)
  • 如果超时(此处为 3 秒),它将调用错误回调

一个活生生的例子:

hasFont("Open Sans", function() {
  document.body.innerHTML += " OK<br>Loading font..."

  // unknown font:
  hasFont("xFontoY", function() {
    document.body.innerHTML += " OK"
  }, function() {
    document.body.innerHTML += " Not loaded"
  });
  
}, function() {
  document.body.innerHTML += " Not loaded"
});

function hasFont(fontName, callback, error) {

  var canvas = document.createElement("canvas"),
      ctx = canvas.getContext("2d"),
      w = 60, h = 20,                             // affects accuracy
      delay = 50, maxTests = (1000 / delay) * 3,  // 3 sec @ 50ms intervals
      initial = getPixels("sans-serif");
  
  canvas.width = w; canvas.height = h;

  // test
  (function test() {
    var px = getPixels(fontName), len = px.length, i = 0;
    for(; i < len; i++) {
      if (initial[i] !== px[i]) {callback(fontName);return}
    }
    
    if (--maxTests) setTimeout(test, delay);
    else {if (error) error(fontName)}
  })();
  
  function getPixels(fontName) {
    ctx.clearRect(0, 0, w, h);
    ctx.font = h + "px " + fontName + ", sans-serif";
    ctx.fillText("aWm", 0, h);
    return new Uint32Array(ctx.getImageData(0, 0, w, h).data.buffer);
  }
}

@font-face {
  font-family: 'Open Sans';
  font-style: normal;
  font-weight: 400;
  src: local('Open Sans'), local('OpenSans'), url(https://fonts.gstatic.com/s/opensans/v10/cJZKeOuBrn4kERxqtaUH3VtXRa8TVwTICgirnJhmVJw.woff2) format('woff2'), url(https://fonts.gstatic.com/s/opensans/v10/cJZKeOuBrn4kERxqtaUH3T8E0i7KZn-EPnyo3HZu7kw.woff) format('woff');
}
canvas {border:1px solid #000}

Loading font...

随意重写它以获取选项、承诺等.

Feel free to rewrite it to take options, promise etc.

相关文章