微信小程序canvas绘制简单饼状图

微信小程序canvas绘制简单饼状图

  <canvas type="2d" id="circle1" style="width: 374rpx; height: 374rpx;"></canvas>
Page({
    /**
     * 页面的初始数据
     */
    data: {
    //canvas 渲染的数据
    canvasData: {
          all:"30",
          colors:["#37BEA4", "#FDE61B", "#2886D8", "#9A3CE8", "#E05262", "#316316", "#FDB32C", "#A28888"],
          name:"总量",
          valueList:[6,5,3,4,5,6,7,8]
        },
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
    // 通过 SelectorQuery 获取 Canvas 节点,这是关键点
        wx.createSelectorQuery()
          .select('#circle1')
          .fields({
            node: true,
            size: true,
          })
          .exec(this.init.bind(this))
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },
    //canvas方法
  init(useElectricity) {
    const width = useElectricity[0].width
    const height = useElectricity[0].height
    const canvas = useElectricity[0].node
    const ctx = canvas.getContext('2d')
    const dpr = wx.getSystemInfoSync().pixelRatio;
    const unit = wx.getSystemInfoSync().windowWidth / 375;
    canvas.width = width * dpr
    canvas.height = height * dpr
    ctx.scale(dpr, dpr)
    //获取中心坐标
    let centerPoint = {
      x: width / 2,
      y: height / 2
    }
    let item = this.data.canvasData;
    let valueSum = [0]
    if (item.valueList) {
      item.valueList.reduce((pre, itemchild) => {
        valueSum.push(pre + itemchild)
        return pre + itemchild
      }, 0);
    }

    ctx.save();
    // ctx.translate(width / 2, height / 2); //画布移动到中心
    for (let i = 0; i < valueSum.length - 1; i++) {
      ctx.restore();
      ctx.beginPath();
      ctx.lineWidth = 25 * unit;
      ctx.strokeStyle = item.colors[i];
      ctx.arc(centerPoint.x, centerPoint.y, centerPoint.y - 12.5 * unit, (3 * Math.PI / 2) - (valueSum[i] * Math.PI * 2 / valueSum[valueSum.length - 1]), (3 * Math.PI / 2) - ((valueSum[i + 1] * Math.PI * 2) / valueSum[valueSum.length - 1]), true);
      ctx.stroke();
    }
    //画字
    let total = item.all;
    ctx.font = `normal bold ${26*unit}px sans-serif`;
    ctx.textAlign = "center";
    ctx.textBaseline = "middle";
    ctx.fillStyle = "#333333";
    ctx.fillText(total, centerPoint.x, centerPoint.y);
    //文字
    let stateStr = item.name;
    ctx.fillStyle = "#888888";
    ctx.font = `normal ${12*unit}px sans-serif`;
    ctx.textAlign = "center";
    ctx.textBaseline = "bottom";
    ctx.fillText(stateStr, centerPoint.x, centerPoint.y + 25 * unit);
    ctx.draw;
  },


})

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值