1. 程式人生 > >小程序使用Canvas畫餅圖

小程序使用Canvas畫餅圖

tar lin canvas style nload raw 代碼 程序 function

先上效果圖

技術分享圖片

-------------------------------------------------------------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代碼結束--------------------------------------------------------------------

小程序使用Canvas畫餅圖