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

How to add a border on HTML5 Canvas' Text?

1个答案

1

Steps:

  1. Obtain the Canvas element and context: First, acquire the Canvas element and its 2D rendering context. This forms the foundation for all Canvas drawing operations.
  2. Set text styles: Before rendering text, configure properties such as font size, font type, and text color.
  3. Use the fillText() method to draw text: Employ the fillText() method to render plain text on the Canvas.
  4. Set border styles: Define properties like border color and width, which will apply to the subsequent strokeText() method.
  5. Use the strokeText() method to draw the text border: Render the text border at the same position using strokeText() to enhance text visibility.

Example code:

html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Canvas Text Border Example</title> </head> <body> <canvas id="myCanvas" width="300" height="200" style="border:1px solid #000000;"></canvas> <script> var canvas = document.getElementById('myCanvas'); var ctx = canvas.getContext('2d'); // Set text styles ctx.font = '24px Arial'; ctx.fillStyle = 'blue'; // Draw plain text ctx.fillText('Hello, Canvas!', 50, 100); // Set border styles ctx.lineWidth = 1; ctx.strokeStyle = 'red'; // Draw text border ctx.strokeText('Hello, Canvas!', 50, 100); </script> </body> </html>

Effect description:

In the provided code, the fillText() method first renders "Hello, Canvas!" in blue. Next, the border color is set to red, and strokeText() draws the border at the same position. This creates a prominent red border, boosting visual impact and contrast. Adjusting ctx.lineWidth and ctx.strokeStyle allows customization of border styles.

2024年8月14日 23:41 回复

你的答案