Skip to content Skip to sidebar Skip to footer

Using Local Fonts In Drawing Html5 Canvas Text

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?

Solution 1:

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

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

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

// load google font == MonotonWebFontConfig = {
  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");

functionstart(){
  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><canvasid="canvas"width=400height=100></canvas>

Solution 2:

You can specify any font to the canvas. You should be able to type anything that CSS would accept

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.font = "Arial 30px";

Post a Comment for "Using Local Fonts In Drawing Html5 Canvas Text"