2021-08-13 cavas实现旋转五角星

先看看效果

<!DOCTYPE html>
<html>

<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        canvas {
            border: 1px solid #000;
        }
    </style>
</head>

<body>
    <canvas width="800" height="600"></canvas>
    <script>
        var canvas = document.querySelector('canvas'); // 获取canvas的dom节点
        var ctx = canvas.getContext('2d'); // 绘制上下文
        // 创建渐变色
        var gradient = ctx.createLinearGradient(240, 0, canvas.width, 0);
        gradient.addColorStop("0", "magenta");
        gradient.addColorStop("0.5", "blue");
        gradient.addColorStop("1.0", "red");
        //角度 1deg=角度/180*Math.PI
        //x轴  y轴
        ctx.beginPath(); // 设置一个起始起始路径
        ctx.translate(400, 300);
        var timer = setInterval(function() {
            //4.清除的点需要注意         
            ctx.clearRect(-151, -101, canvas.width, canvas.height);
            //1.定义一个旋转的方法,确定每次时间间隔中要旋转多少弧度
            ctx.rotate(0.01 * Math.PI);
            //2.绘制一个矩形,因为需求要求矩形以中心为轴进行旋转,但是canvas中rotate只能以画布左上角为轴,进行旋转
            //因此,只要使矩形的中心和画布的左上角重合就可以了(起点的横纵坐标为矩形宽高的一半)
            function draw(ctx, x, y, R, r, fillStyle, strokeStyle) {
                ctx.beginPath();
                for (var i = 0; i < 5; i++) {
                    ctx.lineTo(Math.cos((18 + 72 * i) / 180 * Math.PI) * R + x, -Math.sin((18 + 72 * i) / 180 * Math.PI) * R + y);
                    ctx.lineTo(Math.cos((54 + 72 * i) / 180 * Math.PI) * r + x, -Math.sin((54 + 72 * i) / 180 * Math.PI) * r + y);
                }
                ctx.closePath();
                ctx.lineWidth = 4; //宽度为4
                ctx.fillStyle = fillStyle; //填充颜色为粉色
                ctx.fill(); // 填充;
                ctx.strokeStyle = strokeStyle; //描边颜色
                ctx.stroke(); //描边
            }
            draw(ctx, 0, 0, 100, 50, 'pink', gradient);
        }, 100);
        ctx.closePath(); // 关闭路径
    </script>
</body>

</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值