微信小程序绘制饼状图

微信小程序绘制饼状图_第1张图片

	.xml
	  <view class="left">
      <cover-view class="white"></cover-view>
      <canvas style="width: 136px; height: 136px;" canvas-id="Canvas"></canvas>
    </view>
	.wxss
	.left {
	width: 300rpx;
	height: 300rpx;
	display: flex;
	justify-content: center;
	align-items: center;
	position: relative;
}
 
.white {
	width: 136rpx;
	height: 136rpx;
	border-radius: 50%;
	position: absolute;
	top: 50%;
	left: 50%;
	z-index: 10;
	background-color: #fff;
	transform: translate(-50%, -50%);
}
.js
data: {
    messarr: [{
      color: '#5fb0f1',
      num: '20',
      flownum: '20',
    },
    {
      color: '#ffb822',
      num: '50',
      flownum: '50',
    },
    {
      color: '#e4007f',
      num: '60',
      flownum: '60',
    },
    {
      color: '#ff0000',
      num: '80',
      flownum: '80',
    }
  ]

  },
  /**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function() {
    // 初始化
  const ctx = wx.createCanvasContext('Canvas');
  // 设置圆点 x  y   中心点
  let number = {
    x: 68,
    y: 68
  };
  // 获取数据 各类项的个数
  let term = this.data.messarr;
  let termarr = [];
  for (let t = 0; t < term.length; t++) {
    // flownum
    let thisterm = Number(term[t].flownum)
    let thiscolor = term[t].color
    termarr.push({
      data: thisterm,
      color: thiscolor
    })
  }
  console.log(termarr)
  // 设置总数
  let sign = 0;
  for (var s = 0; s < termarr.length; s++) {
    sign += termarr[s].data
  }
  //设置半径 
  let radius = 60;
  for (var i = 0; i < termarr.length; i++) {
    var start = 0;
    // 开始绘制
    ctx.beginPath()
    if (i > 0) {
      for (var j = 0; j < i; j++) {
        start += termarr[j].data / sign * 2 * Math.PI
      }
    }
    var end = start + termarr[i].data / sign * 2 * Math.PI
    ctx.arc(number.x, number.y, radius, start, end);
    ctx.setLineWidth(1);
    ctx.lineTo(number.x, number.y);
    ctx.setStrokeStyle('#fff');
    ctx.setFillStyle(termarr[i].color);
    ctx.fill();
    ctx.closePath();
    ctx.stroke();
  }
  ctx.draw()
},

不喜欢多说废话所以直接上代码,是我状态的项目需求通过参考其他博主文章才成功的,忘记是哪篇文章了所以也没有转载连接

你可能感兴趣的:(css,html)