1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
| <!DOCTYPE html> <html lang="zh_CN">
<head> <title>绘制曲线和路径(绘制正多边形)</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content="图形系统开发实战:基础篇 示例"> <meta name="author" content="hjq"> <meta name="keywords" content="canvas,anygraph,javascript,图形"> <script src="../js/helper.js"></script> </head>
<body style="margin:10px;"> <canvas id="canvas" width="800" height="400" style="border:solid 1px #CCCCCC; "></canvas> </body> <script> let canvas = document.getElementById('canvas'); let ctx = canvas.getContext('2d');
for (let i = 3; i < 8; i++) { drawRegularPolygon(ctx, 150 * (i - 3) + 100, 100, 50, i, { "color": "blue", "lineWidth": 4 });
drawRegularPolygon(ctx, 150 * (i - 3) + 100, 250, 50, i, { "fillColor": "red" }); }
function drawRegularPolygon(ctx, x, y, size, sideNum, style) { let coords = _getEdgeCoords(size, sideNum); let num = coords.length; ctx.beginPath(); for (let i = 0; i < num; i++) { let point = coords[i]; if (i == 0) { ctx.moveTo(x + point[0], y + point[1]); } else { ctx.lineTo(x + point[0], y + point[1]); } } ctx.closePath(); if (style.fillColor == null || style.fillColor === "none") { ctx.strokeStyle = style.color; ctx.lineWidth = style.lineWidth == null ? 1 : style.lineWidth; ctx.stroke(); } else { ctx.fillStyle = style.fillColor; ctx.fill(); } }
function _getEdgeCoords(size, sideNum) { let vPoint = []; let arc = Math.PI / 2 - Math.PI / sideNum; let r = size; for (let i = 0; i < sideNum; i++) { arc = arc - 2 * Math.PI / sideNum; vPoint[i] = [r * Math.cos(arc), r * Math.sin(arc)]; } return vPoint; } </script>
</html>
|