简体   繁体   中英

External Font on HTML5 Canvas

I am completely baffled as to how to change the font I'm using when drawing text on a canvas. The following is the font I have defined in my CSS:

@font-face{
 font-family:"Officina";
 src:url(OfficinaSansStd-Book.otf);
}

Now in my HTML/JavaScript I'm tempted to say:

context.font = '30px "Officina"';

But this doesn't work. It works fine if I use a web available font (like Arial), and the Officina font shows up fine when I just write plain text directly to the webpage. What am I missing?

To get cross-browser compatibility you should use CSS for the embedded font like this:

@font-face {
    font-family: 'BankGothicMdBTMedium';
    src: url('bankgthd-webfont.eot');
    src: local('BankGothic Md BT'), local('BankGothicBTMedium'), url('bankgthd-webfont.woff') format('woff'), url('bankgthd-webfont.ttf') format('truetype'), url('bankgthd-webfont.svg#webfontNgZtDOtM') format('svg');
    font-weight: normal;
    font-style: normal;
}

Note: I got those font files somewhere at http://fontsquirrel.com

This is working for me, but I'm using this font also in HTML markup, so maybe a workaround (if the font-face definition doesn't help) can be using that font in some hidden div , of course I'm running all JS after body loads.

You can use the Google Web Font loader, but that's rather heavyweight and/or annoying for many uses. Instead, I'll recommend Jennifer Simonds' FontDetect library , available on GitHub:

A JavaScript class you can use to determine whether a webfont got loaded, which font is being used by an element, or react to a webfont getting loaded (or failing to load).

对于大约2017年以后出现这个问题的人来说,最好使用由Google和Typekit共同制作的Web Font Loader: - https://github.com/typekit/webfontloader

You can load fonts with the FontFace API before using it in the canvas:

// new FontFace(familyName, fontSrc, descriptorOnly)
const myFont = new FontFace('My Font', 'url(https://myfont.woff2)');

myFont.load().then((font) => {
  document.fonts.add(font);

  console.log('Font loaded');
});

The font resource myfont.woff2 is first downloaded. Once the download completes, the font is added to the document's FontFaceSet.

The specification of the FontFace API is a working draft at the time of this writing. See browser compatibility table here .

Then, you can use the font parameter to set your font family.

var ctx = document.getElementById('c').getContext('2d');
var kitty = new Image();
kitty.src = 'http://i954.photobucket.com/albums/ae30/rte148/891blog_keyboard_cat.gif';
kitty.onload = function(){
  ctx.drawImage(this, 0,0,this.width, this.height);
  ctx.font         = '68px KulminoituvaRegular';
  ctx.fillStyle = 'orangered';
  ctx.textBaseline = 'top';
  ctx.fillText  ('Keyboard Cat', 0, 270);
};

Note:

  1. You can simply load your font using "@font-face" CSS, but remember, before you draw on canvas, your font must be loaded to the document.

  2. All of your fonts and images (actually all resources) should be and must be within the same origin or cors-origin enabled, otherwise most of the browser will reject the.network request.

NOTE: Outdated as of 2016

Use this trick and bind an onerror event to an Image element.

Demo here: http://jsfiddle.net/g6LyK/ — works on the latest Chrome.

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

var link = document.createElement('link');
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = 'http://fonts.googleapis.com/css?family=Vast+Shadow';
document.getElementsByTagName('head')[0].appendChild(link);

// Trick from https://stackoverflow.com/questions/2635814/
var image = new Image;
image.src = link.href;
image.onerror = function() {
    ctx.font = '50px "Vast Shadow"';
    ctx.textBaseline = 'top';
    ctx.fillText('Hello!', 20, 10);
};

How about try to put your url as a string:

@font-face{
 font-family:"Officina";
 src:url('OfficinaSansStd-Book.otf');
}

context.font = "30px Officina";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM