Neena Vivek
Neena Vivek

Reputation: 717

Unable to use a Google font on Canvas

This is my code:

img.onload = function() {

  ctx.drawImage(img, 0, 0, 600, 480);

  ctx.lineWidth  = 4;
  ctx.font = "3em 'Lato'";
  ctx.strokeStyle = 'black';
  ctx.fillStyle = 'white';

  var text = 'Custom Text';
  text = text.toUpperCase();
  x = canvas.width/2;
  y = canvas.height - canvas.height/4.5;
  ctx.strokeText(text, x, y);
  ctx.fillText(text, x, y);
}

The font on the canvas is not Lato. After reading other answers, I thought it may be because I am not using it on any other HTML element but then I also added a heading that uses the Lato font. Is there anything else that can cause this issue?

Upvotes: 5

Views: 8785

Answers (4)

Melissa
Melissa

Reputation: 334

Here is a working example based on the MDN example. What's missing from the MDN example is document.fonts.add:

const image = document.getElementById("canvas");

let myFont = new FontFace(
  "Pangolin",
  "url(https://fonts.gstatic.com/s/pangolin/v6/cY9GfjGcW0FPpi-tWMfN79z4i6BH.woff2)"
);

myFont.load().then((font) => {
  document.fonts.add(font);
  console.log("Font loaded");
  var ctx = image.getContext("2d");
  ctx.fillStyle = "#292929";
  ctx.font = "30px Pangolin";
  ctx.fillText("A chicken", 0, 30);
});
<canvas id="canvas"></canvas>

Upvotes: 8

Julien Zakaib
Julien Zakaib

Reputation: 194

I think you may just have a malformed font string. Try removing the quotes around the font-family:

ctx.font = "3em Lato";

Upvotes: 0

Donald Wu
Donald Wu

Reputation: 718

Try this

ctx.font = "3em Lato";

Upvotes: 0

user2345
user2345

Reputation: 3227

Try using this code before starting using the canvas:

var f = new FontFace("Lato", /* url */);
  f.load().then(function() {
    // Ready to use the font in a canvas context
});

From: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/font

Upvotes: 2

Related Questions