欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

小程序使用Canvas画饼图

程序员文章站 2022-04-11 21:21:33
先上效果图 wxml代码开始 wxml代码结束 js代码开始 Page({ data: ......

先上效果图

小程序使用Canvas画饼图

-------------------------------------------------------------wxml代码开始---------------------------------------------------------------

<view class="canvas-content">
<canvas canvas-id="canvas" style="width:100%;height:360px;"></canvas>
</view>

-------------------------------------------------------------wxml代码结束---------------------------------------------------------------

 

 

 

-------------------------------------------------------------js代码开始--------------------------------------------------------------------

page({
data: {

},
onload: function () {
var context = wx.createcanvascontext('canvas', this);
var array = [20, 50, 60,80];
var colors = ["#228b22","pink", "#008b8b", "#adff2f"];
var total = 0;
for (var val = 0; val < array.length; val++) {
total += array[val];
}
var point = { x: 160, y: 120 };
var radius = 100;
for (var i = 0; i < array.length; i++) {
context.beginpath();
var start = 0;
if (i > 0) {
for (var j = 0; j < i; j++) {
start += array[j] / total * 2 * math.pi;
}
}
var end = start + array[i] / total * 2 * math.pi;
context.arc(point.x, point.y, radius, start, end);
context.setlinewidth(2)
context.lineto(point.x, point.y);
context.setstrokestyle('#f5f5f5');
context.setfillstyle(colors[i]);
context.fill();
context.closepath();
context.stroke();
}
context.draw();
}
})

-------------------------------------------------------------js代码结束--------------------------------------------------------------------