使用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()
方法来描边和填充星星。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构