I'm trying to import google fonts into javascript, so I can use the fonts to draw text on my canvas. The problem is that I am receiving errors.
Error 1:Failed to decode download fonts
Error 2:OTS parsing error
This is for a web page I'm developing, and I looked up the problems, but the solutions they suggested, I don't understand.
<!DOCTYPE html>
<html lang = "en">
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<script>
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
var pacifico_font = new FontFace('Pacifico', 'url(https://fonts.googleapis.com/css?family=Pacifico&display=swap)');
pacifico_font.load().then(function(loaded_face) {
document.fonts.add(loaded_face);
document.body.style.fontFamily = '"Pacifico", Pacifico';
}).catch(function(error) {
alert("An error occured, please continue.");
});
document.fonts.ready.then(function(font_face_set) {
var x = true;
return x;
});
ctx.fillStyle=rgb(0,0,0);
if(x===true){
ctx.font="20px Pacifico";
ctx.fillText("Hello Cody(testing)",200,200);
}
</script>
</body>
</html>
I expect the canvas to show text, but it alert me to that there was an error, and there is nothing.
In the console it says:
Failed to decode downloaded font: https://fonts.googleapis.com/css?family=Pacifico&display=swap
OTS parsing error: invalid version tag
You are loading a stylesheet not a font.
Here is the solution:
<!DOCTYPE html>
<html lang = "en">
<head>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Pacifico&display=swap">
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<!--window.onload won't work without this because there is nothing waiting for the link to load-->
<span id="loader" style="font-family: Pacifico;">I am used for loading</span>
<script>
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
ctx.fillStyle="rgb(0,0,0)";
window.onload = function() {
document.getElementById("loader").style.display="none"
ctx.font="20px Pacifico";
ctx.fillText("I am inside of canvas",200,200);
ctx.stroke();
}
</script>
</body>
</html>