canvas绘制多边形
canvas封装绘制多边形方法,通过传参来实现绘制图形的定制需要。
1 2
| <canvas width = 400 height = 400 id = "canvas" > </canvas>
|
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
| function angleToRadian(angle) { return angle * Math.PI / 180; };
function getAxisPoints(side, r, offsetX, offsetY) {
var angle = 360 / side; var axisArr = []; for (var i = 0; i < side; i++) {
var x = offsetX + Math.cos(angleToRadian(angle * (i + 1))) * r; var y = offsetY + Math.sin(angleToRadian(angle * (i + 1))) * r; axisArr.push({ x, y }) }; return axisArr; };
var _axisArr = getAxisPoints(3, 150, 200, 200);
var canvas = document.querySelector("#canvas"); var txt = canvas.getContext("2d"); txt.beginPath(); txt.moveTo(_axisArr[0].x, _axisArr[0].y); _axisArr.map(function(item, index) { if (index > 0) { txt.lineTo(_axisArr[index].x, _axisArr[index].y) } }); txt.lineTo(_axisArr[0].x, _axisArr[0].y); txt.strokeStyle = "#000"; txt.stroke();
|