..._小程序饼状图">
赞
踩
写在前:按照比例绘制饼状图
实现效果:
布局
- <view class="left">
- <cover-view class="white"></cover-view>
- <canvas style="width: 136px; height: 136px;" canvas-id="Canvas"></canvas>
- </view>
样式
- page {
- width: 100%;
- height: 100%;
- }
-
- .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%);
- }
实现效果
- Page({
-
- /**
- * 页面的初始数据
- */
- data: {
- messarr: [{
- color: '#464af8',
- num: '20',
- flownum: '20',
- },
- {
- color: '#ff6262',
- num: '50',
- flownum: '50',
- },
- {
- color: '#f7c11b',
- num: '60',
- flownum: '60',
- },
- {
- color: '#ff8015',
- num: '80',
- flownum: '80',
- },
- {
- color: '#17d0bc',
- num: '20',
- flownum: '20',
- }
- ]
- },
-
- /**
- * 生命周期函数--监听页面加载
- */
- onLoad: function(options) {
-
- },
-
- /**
- * 生命周期函数--监听页面初次渲染完成
- */
- 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()
- },
-
- })
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。