Canvas 绘制饼图,绘制出来的不是圆形,大小也不一样
number: [
{
type: 'male',
color: '#ff6262',
data: '15',
},
{
type: 'female',
color: '#f7c11b',
data: '20',
},
{
type: 'other',
color: '#ff8015',
data: '15',
},
]
const query = this.createSelectorQuery();
query.select('#canvas')
.fields({ node: true, size: true })
.exec((res) => {
const canvas = res[0].node;
const ctx = canvas.getContext('2d');
console.log("ctx---", ctx);
// 设置圆点 x y 中心点
let point = {
x: canvas._width/2,
y: canvas._height/2,
r: 30
};
ctx.moveTo(point.x, point.y);
// 获取数据 各类项的个数
let temp = this.data.number;
// 设置总数
let sign = 50;
for (let i = 0; i < temp.length; i++) {
let start = 0;
// 开始绘制
ctx.beginPath()
if (i > 0) {
for (let j = 0; j < i; j++) {
start += temp[j].data / sign * 2 * Math.PI
}
};
let end = start + temp[i].data / sign * 2 * Math.PI;
ctx.fillStyle = temp[i].color;
ctx.moveTo(point.x, point.y);
ctx.arc(point.x, point.y, point.r, start, end, false);
ctx.lineTo(point.x, point.y);
ctx.fill();
// ctx.closePath();
};
// let img = ctx.createImage();
// img.onload = (res) => {
// console.log('onload成功')
// ctx.drawImage(img, 52, 52, 104, 104);
// }
});
<view class="chart">
<canvas id="canvas" type="2d" style="width: 104px; height: 104px; display: inline-block;"></canvas>
</view>
.chart {
width: 208rpx;
height: 208rpx;
background-color: #EEC18C;
filter: drop-shadow(2px 9px 6px rgba(32,26,49,0.29));
-webkit-filter: drop-shadow(2px 9px 6px rgba(32,26,49,0.29));
border-radius: 100%;
position: absolute;
top: 0;
bottom: 0;
left: 128rpx;
margin: auto 0;
}