How to write text into an HTML canvas
If you want to write text into an HTML canvas, follow these steps:
Set the size of the canvas: To do this, you can either use CSS or the HTML
width
andheight
attributes. For example, if you want a canvas size of 200 x 400, you can use the following code:1
<canvas width="200" height="400"></canvas>
Additionally, make sure to set the
width
andheight
properties of the canvas object in JavaScript to avoid blurry text rendering. For example:1
2canvas.width = 1800;
canvas.height = 1200;Get a reference to the canvas: Use the
querySelector
method to select the canvas element. For example:1
const canvas = document.querySelector('canvas');
Create a context object from the canvas: Use the
getContext
method and pass'2d'
as the argument. This creates a 2D rendering context for the canvas.1
const context = canvas.getContext('2d');
Use the
fillText()
method to write text: Now that you have the context object, you can call thefillText()
method to write text on the canvas. Specify the text content and the starting coordinates. For example:1
context.fillText('hi!', 100, 100);
Make sure the starting coordinates are within the canvas size.
Customize the appearance: You can customize the appearance of the text by setting additional properties before calling
fillText()
. For example, you can change the font, fill style, etc. Here’s an example:1
2
3context.font = 'bold 70pt Menlo';
context.fillStyle = '#ccc';
context.fillText('hi!', 100, 100);
By following these steps, you can effectively write text into an HTML canvas.
tags: [“HTML canvas”, “JavaScript”, “text rendering”, “2D rendering”, “fillText”, “canvas size”]