使用canvas制作一个星星
在前端开发中,使用HTML5的<canvas>元素可以创建各种图形,包括星星。以下是一个简单的示例,说明如何使用canvas制作一个五角星:
- HTML结构:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Canvas Star</title>
</head>
<body>
<canvas id="myCanvas" width="400" height="400" style="border:1px solid #000;"></canvas>
<script src="script.js"></script>
</body>
</html>
- JavaScript代码 (
script.js文件):
window.onload = function() {
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
var cx = canvas.width / 2;
var cy = canvas.height / 2;
var spikes = 5; // 星星的角数
var outerRadius = 100; // 外半径
var innerRadius = 50; // 内半径
var rot = Math.PI / 2 * 3; // 旋转起始角度
var x = cx;
var y = cy;
var step = Math.PI / spikes; // 每个角之间的角度
ctx.beginPath();
ctx.moveTo(cx, cy - outerRadius); // 从顶部点开始
for (var i = 0; i < spikes; i++) {
x = cx + Math.cos(rot) * outerRadius;
y = cy + Math.sin(rot) * outerRadius;
ctx.lineTo(x, y); // 画到外点
rot += step; // 更新角度
x = cx + Math.cos(rot) * innerRadius;
y = cy + Math.sin(rot) * innerRadius;
ctx.lineTo(x, y); // 画到内点
rot += step; // 更新角度
}
ctx.lineTo(cx, cy - outerRadius); // 回到起始点,闭合路径
ctx.closePath();
ctx.lineWidth = 5; // 设置线宽
ctx.strokeStyle = 'gold'; // 设置描边颜色
ctx.stroke(); // 描边
ctx.fillStyle = 'yellow'; // 设置填充颜色
ctx.fill(); // 填充
};
这段代码首先定义了canvas的上下文、中心点和星星的一些基本属性(如角数、内外半径等)。然后,它使用beginPath()开始一个新的路径,并使用一系列lineTo()方法来定义星星的形状。最后,它使用stroke()和fill()方法来描边和填充星星。
浙公网安备 33010602011771号