In HTML5 Canvas, the fillRect method is used to draw and fill a rectangle with color, but it does not include a direct parameter for setting a border. To add a border to the rectangle drawn with fillRect, you can use the strokeRect method.
Here are the specific steps and examples:
1. Setting the Canvas Environment
First, create a <canvas> element in HTML and obtain its 2D context in JavaScript.
html<canvas id="myCanvas" width="200" height="200"></canvas>
javascriptvar canvas = document.getElementById('myCanvas'); var ctx = canvas.getContext('2d');
2. Using the fillRect Method to Fill a Rectangle
Use the fillRect method to draw a filled rectangle.
javascriptctx.fillStyle = '#FF0000'; // Red fill ctx.fillRect(50, 50, 100, 100); // Draw a rectangle at (50,50) with size 100x100
3. Using the strokeRect Method to Add a Border
At the same position and size, use strokeRect to add a border.
javascriptctx.strokeStyle = '#000000'; // Black border ctx.lineWidth = 5; // Border width of 5 pixels ctx.strokeRect(50, 50, 100, 100); // Draw the border at the same position and size
Complete Example Code
Combining the above steps, the complete HTML and JavaScript code is as follows:
html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Canvas FillRect with Border</title> </head> <body> <canvas id="myCanvas" width="200" height="200"></canvas> <script> var canvas = document.getElementById('myCanvas'); var ctx = canvas.getContext('2d'); // Fill rectangle ctx.fillStyle = '#FF0000'; ctx.fillRect(50, 50, 100, 100); // Border ctx.strokeStyle = '#000000'; ctx.lineWidth = 5; ctx.strokeRect(50, 50, 100, 100); </script> </body> </html>
By doing this, you can add a clear border to the rectangle drawn with the fillRect method. This approach is particularly useful for developing games, graphical user interfaces, or any application that requires rectangular frames.