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
widthandheightattributes. For example, if you want a canvas size of 200 x 400, you can use the following code:<canvas width="200" height="400"></canvas>Additionally, make sure to set the
widthandheightproperties of the canvas object in JavaScript to avoid blurry text rendering. For example:canvas.width = 1800; canvas.height = 1200; -
Get a reference to the canvas: Use the
querySelectormethod to select the canvas element. For example:const canvas = document.querySelector('canvas'); -
Create a context object from the canvas: Use the
getContextmethod and pass'2d'as the argument. This creates a 2D rendering context for the canvas.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: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:context.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.