继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

Canvas水波效果

BIG阳
关注TA
已关注
手记 474
粉丝 73
获赞 458
效果图

webp

water.gif

完整代码
<!DOCTYPE html><html lang="en"><head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Javascript水波图</title>
  <style>
    html,    body {      width: 100%;      height: 100%;      padding: 0;      margin: 0;      overflow: hidden;
    }  </style></head><body>

  <canvas id="water"></canvas>

  <script>
    // 兼容的requestAnimationFrame函数
    let requestAnimationFrame = (function () {      return window.requestAnimationFrame || webkitRequestAnimationFrame || mozRequestAnimationFrame || function (
        callback) {        window.setTimeout(callback, 1000 / 60);
      }
    })();    // 封装设置canvas大小的函数
    let setCanvasSize = function () {
      canvas.width = canvas.parentNode.offsetWidth;
      canvas.height = canvas.parentNode.offsetHeight;
    }    // 获取canvas相关
    let canvas = document.querySelector('#water');    let ctx = canvas.getContext('2d');
    setCanvasSize();    // 一些变量
    let boHeight = canvas.height / 30; // 顶峰高度
    let posHeight = canvas.height / 1.1; // 最低高度
    let step = 0; // 初始角度
    let colors = ['rgba(0, 150, 138, 0.6)', 'rgba(0, 150, 138, 0.3)', 'rgba(0, 150, 138, 0.1)'];    // 绘制函数
    let paint = function () {
      ctx.clearRect(0, 0, canvas.width, canvas.height); // 清空画布
      step += 1; // 角度

      // 遍历colors数组,进行绘制
      colors.forEach((item, index) => {
        ctx.fillStyle = item; // 画笔的颜色
        let angle = (step + index * 50) * Math.PI / 180; // 相差的角度
        let deltaHeight = Math.sin(angle) * boHeight; // 线条左边的起点
        let deltaHeightRight = Math.cos(angle) * boHeight; //线条右边的终点
        ctx.beginPath();
        ctx.moveTo(0, posHeight + deltaHeight);
        ctx.bezierCurveTo(canvas.width / 2, posHeight + deltaHeight - boHeight, canvas.width / 2, posHeight +
          deltaHeightRight - boHeight, canvas.width, posHeight + deltaHeightRight); // 绘制贝塞尔曲线
        ctx.lineTo(canvas.width, canvas.height); // 防止右侧出现空隙
        ctx.lineTo(0, canvas.height); // 防止左侧出现空隙
        ctx.closePath();
        ctx.fill();
      })

      requestAnimationFrame(paint); // 自调
    }    // 调用绘制函数
    paint();    // 响应式
    window.onresize = setCanvasSize;  </script></body></html>



作者:daydreammoon
链接:https://www.jianshu.com/p/1cf27327508c


打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP