HarmonyOS JS 怎么实现饼状图?
在开发中我们可以参考 canvans 基本使用
我们今天实现一个 canvas 怎么实现饼状图功能,我们从以下几个方面进行实现
1. 代码实现
2. 运行效果
1. html 代码
<div class="container"> <canvas ref="canvas1" style="width: 400px; height: 400px; background-color: #ffff00;"></canvas> </div>
2. css 代码实现
.container { display: flex; justify-content: center; align-items: center; left: 0px; top: 0px; width: 454px; height: 454px; flex-direction: column; }
3. js 代码实现
export default { data: { title: 'World', nums:[26,15,12,5,25,17], colors:["#983335","#77963f","#5d437c","#35859f","#d1702f","#365e96"], start:0, end:0 }, onShow() { const el = this.$refs.canvas1; const ctx = el.getContext('2d'); ctx.translate(200,200); ctx.rotate(-Math.PI/6);//旋转一定角度更加自然 this. pieChart(this.nums,ctx,this.end,this.colors,this.start); this. pieNum(this.nums,ctx,this.end,this.colors,this.start); }, //绘制圆饼 pieChart(nums,ctx,end,colors,start) { for (var i = 0;i < nums.length; i ++) { ctx.beginPath(); ctx.moveTo(0,0); end += nums[i]/50*Math.PI;//终止角度 ctx.strokeStyle = "white"; ctx.fillStyle = colors[i]; ctx.arc(0,0,150,start,end); ctx.fill(); ctx.closePath(); ctx.stroke(); start += nums[i]/50*Math.PI;//起始角度 } }, //绘制圆饼上的数值 pieNum(nums,ctx,end,colors,start) { for (var i = 0;i < nums.length; i ++) { start = nums[i]/50*Math.PI/2; ctx.rotate(end+start);//旋转数值 ctx.font = "25px scans-serif"; ctx.fillStyle = "#000"; ctx.fillText(nums[i]+"%",100,0); end = nums[i]/50*Math.PI/2; } } }