canvas 2d 环形统计图

其实小程序上面也可以使用 echart 等开源图表库得,而且支持代码包得裁切功能,但是可能我不会用吧,效果不太好,而且我这就一个图,也没什么交互要写,就手撕了一个环形统计图,也算练习一下 canvas 2d 吧。

说到 canvas 2d 可真是头疼,微信官方不知道干嘛吃的,原接口不再维护了,但是 canvas 2d 得文档几乎没有更新,写起来摸不着头脑。如果你也对 canvas 2d 有疑惑,希望这个环形统计图能给你点帮助。

下面是 canvas 的官方文档,api使用也挺重要,可以先了解了解。

https://developers.weixin.qq.com/miniprogram/dev/component/canvas.html

https://developers.weixin.qq.com/miniprogram/dev/api/canvas/CanvasContext.arc.html

先看看效果

在这里插入图片描述

中间得环形图以及里面的文字就是通过 canvas 2d 绘制出来的,下面看代码。

看看代码

  • WXML
<view class="row chart-container">
    <canvas type="2d" class="chart" id="myChart2d" />
    <view class="col center">
        <view class="row-center" wx:for="{
    {chartData}}" wx:key="chartData" style="margin-top:{
      {
      index==0?'0':'16'}}rpx">
            <view class="circle" style="background: {
      {
      item.color}}"></view>
            <view class="project-item font-size-12 flex1 row">
                <view>{
  {item.title}}</view>
                <view class="flex1 margin-left-16"> {
  {item.numb}}</view>
                <view class="margin-left-16"> {
  {item.percent}}%</view>
            </view>
        </view>
    </view>
</view>

这里并不需要多少代码,但是 type 和 id 一定要,而且记得 class 指定宽高。

  • WXSS
.chart {
   
    width: 112px;
    height: 112px;
}

.row{
   
  display:flex; 
  flex-direction:row;
}

.col{
   
  display:flex; 
  flex-direction:column;
}

.row-center{
   
  display:flex; 
  flex-direction:row;
  align-items: center;
}

.flex1{
   
  flex: 1;
}

.center{
   
  margin: auto;
  width: fit-content;
}

.circle {
   
    width: 18rpx;
    height: 18rpx;
    border-radius: 9rpx;
    box-sizing: border-box;
}

.project-item {
   
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #616161;
    line-height: 34rpx;
    margin-left: 8rpx;
}

.margin-left-16{
   
  margin-left: 16rpx;
}

.font-size-12{
   
  font-size: 24rpx;
}

这里就是上面说的指定宽高了,暂时先用 px 作为单位,其他不知道会不会有问题。

  • JS
Component({
   
	
	properties: {
   
        show: {
   
            type: Boolean,
            value: false,
            observer
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值