canvas画矩形带圆角并填充不同的背景色

用canvas画矩形很容易 但是如果让你画带有圆角的就有点头疼了 更变态的就是根据不的条件 分别给出不同的背景 背景就算了吧 还要填充渐变色 下面先看看效果图吧  

 我就没有拿项目里面来说 因为里面太复杂了 就单独抽出一个小demo

这是在微信小程序里面用的  

注意事项:一定要加上 不然的话 会颜色覆盖 反正我就踩到这个坑里一个多小时

      ctx.beginPath();
onLoad: function (options) {
    let ctx = wx.createCanvasContext('share');
    let x=112,
    y =100, r=5, w=10, h=22
    let grds = ctx.createLinearGradient(112,112,112,122);
    grds.addColorStop(1, 'rgba(239, 255, 64, .8)');
    grds.addColorStop(0, 'rgba(246, 137, 72, .8)');
    for(let i = 0;i<10;i++){
      ctx.beginPath(); //一定要加上 不然的话 会颜色覆盖
      ctx.moveTo(x+r, y);
      ctx.arcTo(x+w, y, x+w, y+h, r);
      ctx.arcTo(x+w, y+h, x, y+h, r);
      ctx.arcTo(x, y+h, x, y, r);
      ctx.arcTo(x, y, x+w, y, r);
      if(i<5){
        ctx.fillStyle = grds;//设置填充颜色
        ctx.closePath();
        ctx.fill()
        x+=18
      }else{
        ctx.fillStyle = 'yellow';//设置填充颜色
        ctx.fill()
        x+=18
      }
    }
    ctx.draw()
  },

后续会把自己画的一个完整复杂样式的模板更新出来及里面分别遇到的坑分享出来

猜你喜欢

转载自blog.csdn.net/xy19950125/article/details/120460994