Reputation: 717
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
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
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
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