在绘制html5画布文本时使用本地字体 [英] using local fonts in drawing html5 canvas text

查看:94
本文介绍了在绘制html5画布文本时使用本地字体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用HTML5画布构建一个像meme生成器这样的简单工具。是否可以在画布上使用移动电话上的本地字体(这是移动设备的目标)?

I'm trying to build a simple tool like meme generator using HTML5 canvas. Is it possible to use local fonts on the mobile phone (this is target towards mobile) in the canvas?

推荐答案

@Akxe正确回答你可以 .fillText 使用本地字体在html5画布上绘制。

@Akxe correctly answers that you can .fillText using local fonts to draw on html5 canvas.

拉出必要的字体也很常见(s)来自各种互联网字体主机。

It's also common to pull necessary font(s) from various internet font hosts.

这是一个如何下载网络字体的例子。在html5画布上绘制它:

Here's an example of how to download a web font & draw with it on html5 canvas:

// load google font == Monoton
WebFontConfig = {
  google:{ families: ['Monoton'] },
  active: function(){start();},
};
(function(){
  var wf = document.createElement("script");
  wf.src = 'https://ajax.googleapis.com/ajax/libs/webfont/1.5.10/webfont.js';
  wf.async = 'true';
  document.head.appendChild(wf);
})();


var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");

function start(){
  ctx.font = '40px Monoton';
  ctx.textBaseline = 'top';
  ctx.fillText('Monoton    Font', 20, 10);
  var width=ctx.textMetrics('No').width;
  console.log(width);
}

body{ background-color: ivory; padding:10px; }
#canvas{border:1px solid red;}

<h4>"Monoton" font drawn on canvas is a downloaded web font</h4>
<canvas id="canvas" width=400 height=100></canvas>

这篇关于在绘制html5画布文本时使用本地字体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆