Drawing text on the HTML5 Canvas element is primarily achieved through the Canvas 2D rendering context, specifically the CanvasRenderingContext2D interface. This interface provides multiple methods and properties related to drawing text. Below, I will walk through the commonly used methods and properties step by step, along with how to use them to draw text.
- Preparing the Canvas Environment
First, add a <canvas> element to your HTML document and obtain its rendering context using JavaScript.
html<canvas id="myCanvas" width="300" height="150"></canvas> <script> var canvas = document.getElementById('myCanvas'); var ctx = canvas.getContext('2d'); </script>
- Setting Text Styles
Before drawing text, you can configure font styles, sizes, alignment, and other properties. Here are some commonly used text style attributes:
font: Defines the text style and size, similar to the CSSfontproperty.textAlign: Sets the text alignment, with possible values including 'left', 'center', and 'right'.textBaseline: Sets the text baseline, with possible values including 'top', 'hanging', 'middle', 'alphabetic', 'ideographic', and 'bottom'.
javascriptctx.font = '20px Arial'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
- Drawing Text
Canvas provides two fundamental methods for drawing text:
fillText(text, x, y, [maxWidth]): Draws the text as a solid fill at the specified (x, y) position.strokeText(text, x, y, [maxWidth]): Draws the text as a stroke (outline) at the specified (x, y) position.
Here, x and y specify the text position, and maxWidth is an optional parameter used to limit the maximum width of the text.
javascriptctx.fillText('Hello, Canvas!', 150, 75); // Draws solid text ctx.strokeText('Hello, Canvas!', 150, 125); // Draws stroked text
Example: Complete Code
html<!DOCTYPE html> <html> <head> <title>Canvas Text Example</title> </head> <body> <canvas id="myCanvas" width="300" height="150" style="border:1px solid #000000;"></canvas> <script> var canvas = document.getElementById('myCanvas'); var ctx = canvas.getContext('2d'); ctx.font = '20px Arial'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.fillText('Hello, Canvas!', 150, 75); // Draws solid text ctx.strokeText('Hello, Canvas!', 150, 125); // Draws stroked text </script> </body> </html>
This example creates a simple Canvas with 'Hello, Canvas!' drawn at its center. By adjusting properties and method parameters, you can achieve more varied text effects.