乐闻世界logo
搜索文章和话题

How can I use custom fonts in an HTML5 Canvas element?

1个答案

1

Using custom fonts in HTML5 Canvas elements primarily involves two steps: first, include the custom font in your HTML document; second, set the font in the Canvas. Below, I will detail these two steps and provide a specific example.

Step 1: Including Custom Fonts

Custom fonts can be included in multiple ways. One common method is to use the CSS @font-face rule. For example, if you have a custom font file named MyCustomFont.ttf, you can declare it in CSS as follows:

css
@font-face { font-family: 'MyCustomFont'; src: url('MyCustomFont.ttf') format('truetype'); }

This code informs the browser where to find the font file and names it MyCustomFont, which can then be referenced in CSS.

Step 2: Using Custom Fonts in Canvas

Once the font is included and available via CSS, you can set it in the Canvas using the font property. It is crucial to ensure the font has loaded completely; otherwise, the font may not apply correctly. You can ensure the font loads completely by using the JavaScript Font Loading API or simple event listeners:

javascript
document.fonts.load('10pt "MyCustomFont"').then(function() { var canvas = document.getElementById('myCanvas'); var ctx = canvas.getContext('2d'); ctx.font = '20px MyCustomFont'; ctx.fillText('Hello, custom font!', 10, 50); });

In this example, document.fonts.load is a function that returns a Promise, ensuring the font loads completely. After the Promise resolves, set the Canvas's font property to your custom font and use fillText() to draw text on the Canvas.

Complete Example

Combining the above two steps, here is a complete HTML example:

html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Canvas Custom Font Example</title> <style> @font-face { font-family: 'MyCustomFont'; src: url('MyCustomFont.ttf') format('truetype'); } </style> </head> <body> <canvas id="myCanvas" width="300" height="100"></canvas> <script> document.fonts.load('10pt "MyCustomFont"').then(function() { var canvas = document.getElementById('myCanvas'); var ctx = canvas.getContext('2d'); ctx.font = '20px MyCustomFont'; ctx.fillText('Hello, custom font!', 10, 50); }); </script> </body> </html>

This example demonstrates how to include and use a custom font in a web page within a Canvas element. This method ensures the font loads completely before use, ensuring correct display.

2024年6月29日 12:07 回复

你的答案