Steps:
- 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.
- Set text styles: Before rendering text, configure properties such as font size, font type, and text color.
- Use the
fillText()method to draw text: Employ thefillText()method to render plain text on the Canvas. - Set border styles: Define properties like border color and width, which will apply to the subsequent
strokeText()method. - Use the
strokeText()method to draw the text border: Render the text border at the same position usingstrokeText()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 回复