美文网首页
小程序canvas弧形进度条

小程序canvas弧形进度条

作者: litielongxx | 来源:发表于2022-02-25 16:22 被阅读0次

canvas弧形进度条,实现如图。


image.png

canvas重绘分数,如rgba底色会覆盖逐渐变白,暂时十六进制。
canvas小程序,如最外view存在 fixed等定位,会飘,截取用替换的图片代替。
起始位置为下图中的0.75-0.25,3/4圆270度。


image.png
<view >
      <canvas class=" canvas"  hidden="{{showCanvaImg}}"  canvas-id="myCanvas" ></canvas>
      <image wx:if="{{showCanvaImg}}" class="score-hu canvas" src="{{canvasImgUrl}}"></image>
</view>
<script>
data() {
  return {
  showCanvaImg:false,// 配合下一个
canvasImgUrl:'' // 替换图片的地址,实际canvas中来
ctx:''// 用同一canvas节省点
 }
}
</scirpt>
//style
.canvas {
width:300px;
height:400px
}
let left = this.data.totalScore * (270 / 120);
    // 分数对应弧度(结束点)
    // 0.75-0.25  
    //  弧线增长的范围  
    let tempPi=1.5/270*left
    
    // 1  因为实际从0.75开始  至少要0.25才能从1开始
    if(tempPi<=0.25) {
      tempPi=0.75+tempPi
    }else if(tempPi>0.25&&tempPi<=1.25) {
      // 2  去除坐标轴下的0.75累赘 直接从
      tempPi=1+tempPi-0.25
    }else if(tempPi>1.25) {
      tempPi=tempPi-1.25
    }

    let left_end = 0.9 + (1.5 / 90) * left;

    if(!this.data.ctx) {
      this.setData({
        ctx:wx.createCanvasContext("myCanvas")
      })
    }
    // const ctx = wx.createCanvasContext("myCanvas");
    
    let ctx=this.data.ctx
    // 画圆环
    ctx.beginPath();
    // x    Number  圆的x坐标
    // y    Number  圆的y坐标
    // r    Number  圆的半径
    // sAngle   Number  起始弧度,单位弧度(在3点钟方向)
    // eAngle   Number  终止弧度
    ctx.arc(84, 90, 75, 0.75 * Math.PI, 0.25 * Math.PI);
    ctx.setStrokeStyle("#769bf7"); // 弧线的颜色
    ctx.setLineWidth("6"); // 弧的宽度
    ctx.setLineCap("round"); //线条结束端点样式 butt 平直 round 圆形 square 正方形
    ctx.stroke();

    // 画进度条 0.9 left_end * Math.PI
    ctx.beginPath();
    ctx.arc(84, 90, 75, 0.75 * Math.PI, tempPi * Math.PI);

    // 为0不画
    if (this.data.totalScore != 0) {
      ctx.setStrokeStyle("#fff");
      ctx.setLineWidth("6");
      ctx.setLineCap("round");
      ctx.stroke();
    }

    let self = this;
    console.log("开始绘图");
    ctx.draw(true, function () {
      wx.canvasToTempFilePath({
        canvasId: "myCanvas",
        success(res) {
          console.log("myCanvasr", res);
          if (res.tempFilePath) {
            self.setData({
              showCanvaImg: true,
              canvasImgUrl: res.tempFilePath,
            });
          }
          console.log("替换图片", res.tempFilePath);
        },
        fail(err) {
          console.log("绘图失败", err);
        },
      });
    });
    console.log("绘图结束");

ps:阻止canvas随页面滚动(已解决,可不看)
https://www.jianshu.com/p/c356ce38fd58

相关文章

网友评论

      本文标题:小程序canvas弧形进度条

      本文链接:https://www.haomeiwen.com/subject/apttrrtx.html