使用canvas制作一个星星

在前端开发中,使用HTML5的<canvas>元素可以创建各种图形,包括星星。以下是一个简单的示例,说明如何使用canvas制作一个五角星:

  1. 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>
  1. 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()方法来描边和填充星星。

posted @   王铁柱6  阅读(6)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示