canvas画布:让立体正五角星转起来
位置:
首页 >
代码集锦[ 发布时间: 2024.5.9 作者: 马黑 阅读: 303 ]
效果
代码
<canvas id="canv" width="400" height="400"></canvas>
<script>
var ctx = canv.getContext('2d');
var size = canv.width / 2, r1 = size - 10, r2 = r1 * 2/5, points = [];
var deg = 0, step = 0.5, mov = true, raf = null;
for(var i = 0; i < 5; i ++) {
var x1 = Math.cos((18 + i * 72) / 180 * Math.PI) * r1 + size,
y1 = -Math.sin((18 + i * 72) / 180 * Math.PI) * r1 + size,
x2 = Math.cos((54 + i * 72) / 180 * Math.PI) * r2 + size,
y2 = -Math.sin((54 + i * 72) / 180 * Math.PI) * r2 + size;
points.push({x1: x1, y1: y1, x2: x2, y2: y2});
}
var draw5star = () => {
for(var j = 0; j < 5; j++) {
ctx.beginPath();
ctx.fillStyle = 'red';
ctx.moveTo(points[j].x1, points[j].y1);
ctx.lineTo(size, size);
ctx.lineTo(points[j].x2, points[j].y2);
ctx.lineTo(points[j].x1, points[j].y1);
ctx.fill();
ctx.beginPath();
ctx.fillStyle = 'darkred';
var k = j > 0 ? j - 1 : 4;
ctx.moveTo(points[j].x1, points[j].y1);
ctx.lineTo(size, size);
ctx.lineTo(points[k].x2, points[k].y2);
ctx.moveTo(points[j].x1, points[j].y1);
ctx.fill();
}
};
var rot = () => {
ctx.clearRect(0, 0, canv.width, canv.height);
ctx.save();
ctx.translate(size, size);
ctx.rotate(deg * Math.PI / 180);
ctx.translate(-size, -size);
draw5star();
ctx.restore();
deg = (deg + step) % 360;
mov ? raf = requestAnimationFrame(rot) : cancelAnimationFrame(raf);
};
canv.onclick = () => {
mov = !mov;
rot();
};
rot();
</script>
前一篇: 在canvas画布中绘制立体正五角星
下一篇: canvas画布:绘制转动的椭圆形环绕文本
发表评论:
评论列表 [1条]
#1 | 飞飞 于 2024-5-9 18:43 发布: 喵~妙~