Created
April 27, 2021 14:43
-
-
Save alexsc6955/06148d596e75a3fce0a5cc1f9394134f to your computer and use it in GitHub Desktop.
Add a custom font to a HTML canvas using javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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