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 90 91 92 93 94
| <!DOCTYPE html> <html>
<head> <title>绘制曲线和路径(Path2)</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,ladder,javascript,图形"> <script src="./js/helper.js"></script> </head>
<body style="overflow: hidden; 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'); drawGrid('lightgray', 10, 10);
for (let i = 5; i < 10; i++) { drawRegularPolygon(ctx, 150 * (i - 5) + 100, 100, 50, i, { "color": "blue", "lineWidth": 4 });
drawRegularPolygon(ctx, 150 * (i - 5) + 100, 250, 50, i, { "fillColor": "red" });
drawText(ctx, "正" + i + "边形", 150 * (i - 5) + 100, 340); }
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; }
function drawText(ctx, text, x, y) { ctx.save(); ctx.textAlign = "center"; ctx.baseAlignline = "bottom"; ctx.font = "bold 18px 黑体"; ctx.fillStyle = "black"; ctx.fillText(text, x, y); ctx.restore(); } </script>
</html>
|