【第2章 绘制】2.11多边形的绘制
文章目录
- 前言
- 简单多边形的绘制
前言
现在,我们已经实现全部的基本图形,包括线段、矩形、圆弧、圆形、贝塞尔曲线等等。但是我们肯定要在canvas中绘制除此之外的其他图形,比如三角形、六边形、八边形等等。在本节中,你将绘学到如何绘制多边形。
使用 moveTo() 与 lineTo() 方法,再结合一些简单的三角函数,就能绘制任意边数的多边形。下面演示了如何根据多边形外接圆的圆心及半径,来计算某个多边形的顶点。
简单多边形的绘制
通过外接圆找到每个顶点的位置,然后根据点的位置依次画出各边即可。
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8" /><title>2-25-多边形的绘制</title></head><body><canvas id="canvas"></canvas><p>试试选择不同的边数</p><label for="sidesSelects">多边形边数</label><select id="sidesSelects"><option selected value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option></select></body><script>'use strict'let canvas = document.getElementById('canvas'),context = canvas.getContext('2d'),sidesSelect = document.getElementById('sidesSelects'),Point = function (x, y) {this.x = xthis.y = y}//Function……/*** 获得多边形的所有外接圆顶点* @param centerX* @param centerY* @param radius* @param sides* @param startAngle*/function getPolygonPoints(centerX, centerY, radius, sides, startAngle) {let points = [],//这里的angle是基于钟表0点的位置开始计算,0点位置为0度,3点位置为π/2度angle = startAngle || 0for (let i = 0; i < sides; ++i) {points.push(new Point(centerX + radius * Math.sin(angle), centerY - radius * Math.cos(angle)))angle += (2 * Math.PI) / sides}return points}/*** 根据每个顶点的位置,创建多边形的路径* @param centerX* @param centerY* @param radius* @param sides* @param startAngle*/function createPolygonPath(centerX, centerY, radius, sides, startAngle) {let points = getPolygonPoints(centerX, centerY, radius, sides, startAngle)context.beginPath()context.moveTo(points[0].x, points[0].y)for (let i = 0; i < sides; ++i) {context.lineTo(points[i].x, points[i].y)}context.closePath()}/*** 绘制多边形*/function drawRubberbandShape() {createPolygonPath(canvas.width / 2, canvas.height / 2, canvas.width / 4, parseInt(sidesSelect.value), 0)context.stroke()}drawRubberbandShape()//eventsidesSelect.onchange = function () {context.clearRect(0, 0, canvas.width, canvas.height)drawRubberbandShape()}</script>
</html>