效果图:
动态变换:
五角星分析
函数调用:
drawNStar(ctx, {
"num":
26,
"R":
150,
"r":
50,
"x":
50,
"y":
50,
"rot":
45
}, {
"fs":
"#F5E322",
"lj":
"round",
"lw":
2,
"b":
true,
"f":
true,
});
函数体:
/**
* 绘制n角星
* @param ctx
* @param num 星星数量
* @param R 中心到顶点距离
* @param r 中心到凹点距离
* @param x 左上角X坐标Y
* @param y 左上角坐标
* @param rot 旋转角度
* @param configJson 配置信息
*/
function _drawNStar(ctx, num, R, r, x, y, rot, configJson) {
b2c(ctx, function () {
var border = configJson[
"lw"];
for (
var i =
0; i < num; i++) {
var perDeg =
360 / num;
var degA = perDeg /
2 /
2;
var degB =
360 / (num -
1) /
2 - degA /
2 + degA;
ctx.lineTo(Math.cos((degA + perDeg * i - rot) /
180 * Math.PI) * R + x + border + R * Math.cos(degA /
180 * Math.PI),
-Math.sin((degA + perDeg * i - rot) /
180 * Math.PI) * R + y + border + R);
ctx.lineTo(Math.cos((degB + perDeg * i - rot) /
180 * Math.PI) * r + x + border + R * Math.cos(degA /
180 * Math.PI),
-Math.sin((degB + perDeg * i - rot) /
180 * Math.PI) * r + y + border + R);
}
}, configJson);
},
function drawNStar(ctx, infoJson, configJson) {
var num, R, r, x, y, rot;
num = infoJson[
"num"];
R = infoJson[
"R"];
r = infoJson[
"r"];
x = infoJson[
"x"];
y = infoJson[
"y"];
rot = infoJson[
"rot"];
_drawNStar(ctx, num, R, r, x, y, rot, configJson)
}
/**
* beginPath到closePath
* @param ctx 上下文
* @param callback 回调函数
* @param configJson 配置信息
*/
function b2c(ctx, callback, configJson) {
ctx.beginPath();
if (callback && typeof(callback) ===
"function") {
callback();
}
ctx.closePath();
ctx.lineWidth = configJson[
"lw"];
ctx.strokeStyle = configJson[
"ss"];
ctx.fillStyle = configJson[
"fs"];
ctx.lineJoin = configJson[
"lj"];
ctx.lineCap = configJson[
"lc"];
if (configJson[
"f"]) {
ctx.fill();
}
if (configJson[
"b"]) {
ctx.stroke();
}
}
动态变换角数
var count =
3;
var timer =
null;
timer = setInterval(
function () {
ctx.fillStyle =
"#fff";
ctx.fillRect(
0,
0, ctx.canvas.width, ctx.canvas.height);
myCanvas.drawNStar(ctx, {
"num": count,
"R":
100,
"r":
50,
"x":
50,
"y":
50,
"rot":
45
}, {
"fs":
"#FCFA31",
"lj":
"round",
"lw":
2,
"f":
true,
});
count++;
console.log(
"{count}--{" + count +
"}");
if (count >
150) {
clearInterval(timer);
}
},
50);
转载于:https://www.cnblogs.com/toly-top/p/9782011.html