我经常使用svgdr设计帖子小播图案,使用过程中越来越觉得计算圆周上的顶点坐标应该封装成一个方法,因此抽空给svgdr增设了一个 circlePoints 指令。该指令的语法和参数解释如下:
dr.circlePoints(points, R, r);
// 参数解释:
// 1. points 顶点数,比如绘制规则六边形,points 参数值就设置为 6
// 2. R 外切圆范围半径,其作用是规范了顶点所在外切圆的圆心
// 3. r 顶点外切圆半径,其值应小于等于 R
指令将返回一个二维数组,数组结构为:[ ["值1","值2"], ["值3","值4"], ["值5","值6"], ..., ["值N","值N+1"] ]。来看看下面绘制规则六边形的例子:通过 circlePoints 指令获得顶点坐标值数组,并将结果组装成多边形的点数据——
<svg id="msvg" width="400" height="400" viewBox="0 0 400 400"></svg>
<script type="module">
import Dr from 'https://638183.freep.cn/638183/web/mod/svgdr.js?v=1';
const dr = Dr.dr(msvg);
// 获取六边形顶点数组
const ar = dr.circlePoints(6, 200, 190);
// 将数组里的数据串接起来
const points = ar.join(',');
// 绘制实心六边形
dr.polygon(points, 'olive');
</script>
再看一个多边形组合图案的绘制例子:
<svg id="msvg" width="400" height="400" viewBox="0 0 400 400"></svg>
<script type="module">
import Dr from 'https://638183.freep.cn/638183/web/mod/svgdr.js?v=1';
const dr = Dr.dr(msvg);
const p1 = dr.circlePoints(8, 200, 190).join(',');
const p2 = dr.circlePoints(8, 200, 160).join(',');
dr.polygon(p1, 'none', 'olive', 3);
dr.polygon(p2, 'none', 'olive', 3);
</script>
灵活使用 circlePoints 指令应该可以绘制出效果炫酷的图案,例如:
<svg id="msvg" width="400" height="400" viewBox="0 0 400 400"></svg>
<script type="module">
import Dr from 'https://638183.freep.cn/638183/web/mod/svgdr.js?v=1';
const dr = Dr.dr(msvg);
const ar1 = dr.circlePoints(18, 200, 190);
const ar2 = dr.circlePoints(18, 200, 160);
let points = '';
for (let j = 0; j < ar1.length; j++) {
let k = (j + 1) % ar1.length;
points += j % 2 === 0 ?
`${ar1[j][0]} ${ar1[j][1]},${ar2[j][0]} ${ar2[j][1]},${ar2[k][0]} ${ar2[k][1]} ` :
`${ar2[j][0]} ${ar2[j][1]},${ar1[j][0]} ${ar1[j][1]},${ar1[k][0]} ${ar1[k][1]} `;
}
points = points.trim();
dr.polygon(points, 'none', 'tan', 3);
</script>
一切取决于创造和实现能力!