Drawing polygons on HTML5 Canvas primarily involves the following steps:
-
Setting up the Canvas: First, create a
<canvas>element in your HTML document and define its width and height. -
Obtaining the Canvas Context: Use JavaScript to access the
2Drendering context of the canvas, which serves as the foundation for drawing. -
Drawing Polygons Using Paths: Leverage the canvas path API to define the polygon's edges.
-
Setting Styles and Colors (Optional): Configure properties such as line color, width, and fill color.
-
Rendering the Path: After defining the path, render the polygon's outline using the
stroke()method or fill it using thefill()method.
Example Code
Suppose you want to draw a pentagon on an HTML page. Follow these steps:
First, add a canvas element to your HTML document:
html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Draw Polygon</title> </head> <body> <canvas id="myCanvas" width="200" height="200" style="border:1px solid #000000;"></canvas> <script src="drawPolygon.js"></script> </body> </html>
Then, in the drawPolygon.js file, write JavaScript code to draw the polygon:
javascriptdocument.addEventListener("DOMContentLoaded", function() { var canvas = document.getElementById('myCanvas'); var ctx = canvas.getContext('2d'); // Start a new path ctx.beginPath(); // Polygon vertex coordinates (for a pentagon) const points = [ {x: 100, y: 10}, {x: 150, y: 60}, {x: 130, y: 130}, {x: 70, y: 130}, {x: 50, y: 60} ]; // Move to the first point ctx.moveTo(points[0].x, points[0].y); // Connect all points with lines for (let i = 1; i < points.length; i++) { ctx.lineTo(points[i].x, points[i].y); } // Close the path by connecting the last point to the first ctx.closePath(); // Set styles ctx.fillStyle = '#FFCC00'; ctx.fill(); ctx.strokeStyle = '#333'; ctx.lineWidth = 5; ctx.stroke(); });
In this example, first move to one vertex of the pentagon using the moveTo() method, then connect the remaining points using the lineTo() method, and use closePath() to automatically close the path (connecting the last point to the starting point). Finally, set the fill color and fill the polygon, set the line color and width, and draw the outline.
When drawing graphics with Canvas, you can flexibly manipulate paths and styles, making it a powerful tool for graphical processing on web pages.