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

How to draw text on canvas?

1个答案

1

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.

  1. 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>
  1. 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 CSS font property.
  • 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'.
javascript
ctx.font = '20px Arial'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
  1. 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.

javascript
ctx.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.

2024年6月29日 12:07 回复

你的答案