Skip to content

Instantly share code, notes, and snippets.

@alexsc6955
Created April 27, 2021 14:43
Show Gist options
  • Save alexsc6955/06148d596e75a3fce0a5cc1f9394134f to your computer and use it in GitHub Desktop.
Save alexsc6955/06148d596e75a3fce0a5cc1f9394134f to your computer and use it in GitHub Desktop.
Add a custom font to a HTML canvas using javascript
var canvas = document.querySelector('canvas');
// we need this to load the font
var myFont = new FontFace('myFont', 'url(assets/fonts/myFont/myFont.otf)');
myFont.load().then(function(font){
// with canvas, if this is ommited won't work
document.fonts.add(font);
console.log('Font loaded');
// set width and height as screen w and h
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
console.log(canvas);
// get canvas context
var ctx = canvas.getContext("2d");
ctx.font = "50px myFont"; // set font
ctx.textAlign = "center"; // center text
ctx.fillText("Hello, World!", canvas.width/2, canvas.height/2); // draw centered text
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment