小程序利用canvas实现波浪动态图,原生canvas的部分限制

小程序的canvas与该动态图的问题

小程序的canvas与html的canvas实现是完全一致的,但是会有一些坑,比如在component使用时会有一些限制,需要绑定this,匹配上下文环境获取canvas,另外看到一种方式,请参考 http://blog.majinyu.xyz/index.php/weapp/canvas-not-work-in-customized-components-in-weapp/,
其次说到该动态图,网上的小程序demo是没有的,因此才写上

首先上效果图片

效果如图所示,会显示一个动态的水波浪,好看的动画背景,适用于很多场景

图片: 小程序利用canvas实现波浪动态图,原生canvas的部分限制

下面直接上代码

html代码片

  <!-- html -->
    <canvas   canvas-id="canvas" class="canvas"></canvas>
  

css代码片


// css
    .canvas {
  width: 305px;
  height: 305px;
  background-color: #fff;
}

js代码片

// javascript
Page({
  onReady: function () {
    this.drawBall()
  },
  drawBall: function () {
    var canvas={
        width:300,
        height:300,
    };
      var boHeight = canvas.height / 10;
      var posHeight = canvas.height / 1.2;
      //初始角度为0 
      var step = 0;
      //定义三条不同波浪的颜色 
      var lines = ["rgba(0,222,255, 0.2)",
          "rgba(157,192,249, 0.2)",
          "rgba(0,168,255, 0.2)"]; 
    var context = wx.createContext();
    debugger
      let requestAnimFrame = (function () {
          return function (callback) {
                  setTimeout(callback, 1000 / 60);
              };
      })();
      function loop() {
          context.clearRect(0, 0, canvas.width, canvas.height);
          step++;
          //画3个不同颜色的矩形 
          for (var j = lines.length - 1; j >= 0; j--) {
              context.fillStyle = lines[j];
              //每个矩形的角度都不同,每个之间相差45度 
              var angle = (step + j * 50) * Math.PI / 180;
              var deltaHeight = Math.sin(angle) * boHeight;
              var deltaHeightRight = Math.cos(angle) * boHeight;
              context.beginPath();
              context.moveTo(0, posHeight + deltaHeight);
              context.bezierCurveTo(canvas.width / 2, posHeight + deltaHeight - boHeight, canvas.width / 2, posHeight + deltaHeightRight - boHeight, canvas.width, posHeight + deltaHeightRight);
              context.lineTo(canvas.width, canvas.height);
              context.lineTo(0, canvas.height);
              context.lineTo(0, posHeight + deltaHeight);
              context.closePath();
              context.fill();
          }
          wx.drawCanvas({
              canvasId: 'canvas',
              actions: context.getActions()
          })
          
          requestAnimFrame(loop);
      }
      loop(); 
  },
})