Using font fonts with fillText canvas

EDIT . Well, it seems that the font loads when it is used by the DOM element, so I just used the hidden Div with the text using the font font, and it works now ... :)

I use this code to update favicon with a number of updates, but I would like to write the number using a custom pixel-font.

This is my javascript code

var canvas = document.createElement('canvas'), ctx, img = document.createElement('img'), link = document.getElementById('favicon').cloneNode(true), updates = data; if (canvas.getContext) { canvas.height = canvas.width = 16; // set the size ctx = canvas.getContext('2d'); img.onload = function () { // once the image has loaded ctx.drawImage(this, 0, 0); ctx.font = 'normal 12px Visitor'; ctx.fillStyle = '#213B55'; ctx.textBaseline="middle"; ctx.textAlign="center"; ctx.fillText(updates, 10, 10); link.href = canvas.toDataURL('image/png'); document.body.appendChild(link); }; img.src = 'favicon_new.png'; } 

This is in my CSS

 @font-face { font-family: 'Visitor'; font -style: normal; font-weight: normal; src: url('fonts/visitor.woff') format('woff'); 

If I change this line:

  ctx.font = 'normal 12px Visitor'; 

With 'normal 12px Arial' works fine. If I use the custom Visitor font, it just changes the icon, but I don’t see it.

Any idea on what might be the problem?

+4
source share
1 answer

Arial is a web-safe font , which means that it will be displayed no matter what computer or mobile device you have (aka fallback).

Here is sample code from Pacifico from Google Fonts (which is not a web font).

 <link href="http://fonts.googleapis.com/css?family=Pacifico" rel="stylesheet" type="text/css"> <script> window.onload=function() { var canvas = document.getElementById("canvas"); var context = canvas.getContext("2d"); context.fillStyle = "blue"; context.font = "16pt Pacifico"; context.fillText("Cursive font", 50, 50); } </script> <canvas id="canvas" width="200" height="200"></canvas> 

This is possible with other fonts.

Make sure @ font-face has font-style: normal; and font-weight: 400; .

+1
source

All Articles