为了账号安全,请及时绑定邮箱和手机立即绑定

Canvas水波效果

标签:
CSS3
效果图

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


点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号

举报

0/150
提交
取消