Canvas画图动态渐变波浪

<!DOCTYPE html>
<html>

<head>
    <style>
        body {
            padding: 0;
            margin: 0;
            overflow: hidden;
            background-image: linear-gradient(to left, #00a2ff, #68de86);
        }

        canvas {
            width: 100%;
            height: 100vh;
        }
    </style>
</head>

<body>
    <canvas id="myCanvas"></canvas>
    <script>
        var num = -1

        // 获取Canvas元素和2D渲染上下文对象
        var canvas = document.getElementById("myCanvas");
        var ctx = canvas.getContext("2d");
        // 定义波浪的属性
        var wave = {
            y: canvas.height / 2, // 波浪的中心位置
            length: 0.04, // 波浪的长度
            amplitude: 60, // 波浪的振幅
            frequency: 0.0003 // 波浪的频率
        };
        // 创建线性渐变对象并添加颜色停止点
        var gradient = ctx.createLinearGradient(0, 0, canvas.width, 0);
        gradient.addColorStop(0, "#00a2ff");
        gradient.addColorStop(1, "#68de86");
        // 绘制波浪的函数
        function drawWave() {
            // 使用requestAnimationFrame实现动画效果
            requestAnimationFrame(drawWave);
            // 清除画布上的任何内容
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            // 开始绘制路径
            ctx.beginPath();
            // 将路径的起点移动到波浪的中心位置
            ctx.moveTo(0, wave.y);
            // 遍历整个画布的宽度,计算每个点的x坐标和y坐标,并将路径连接到该点
            for (var i = 0; i < canvas.width; i++) {
                // 将当前循环的索引值赋给变量x
                var x = i;
                // 根据波浪的属性计算y坐标的值
                var y = wave.y + wave.amplitude * Math.sin(x * wave.length + wave.frequency * Date.now());
                y = y + (x * Math.sin(wave.length + wave.frequency * Date.now()));
                // 将当前点与下一个点的连线添加到路径中
                ctx.lineTo(x, y);
            }
            // 将路径闭合
            ctx.lineTo(canvas.width, canvas.height);
            ctx.lineTo(0, canvas.height);
            ctx.closePath();
            // 设置填充样式为渐变对象,并填充路径
            ctx.fillStyle = gradient;
            ctx.fill();
        }
        // 调用drawWave函数开始绘制波浪动画
        drawWave();

    </script>
</body>

</html>

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值