微信小程序F2饼形图的引入和赋值

js

import F2 from "../../../../components/f2-canvas/lib/f2"
let pie = null;
function setOption(pie,a,b,c,d,e) {
      // F2实现回调的方法,方法名用来最后赋值绑定
  var map = {
     
    '待检查': ((b/a)*100).toFixed(2)+'%',
    '处理中':((c/a)*100).toFixed(2)+'%',
    '流转中':((d/a)*100).toFixed(2)+'%',
    '已结束': ((e/a)*100).toFixed(2)+'%',
  };
  let data = [{
     
      name: '待检查',
      percent: b/a,
      a: '1'
    },
    {
     
      name: '处理中',
      percent: c/a,
      a: '1'
    },
    {
     
      name: '流转中',
      percent: d/a,
      a: '1'
    },
    {
     
      name: '已结束',
      percent: e/a,
      a: '1'
    }
  ];
  pie.source(data, {
     
    percent: {
     
      formatter: function formatter(val) {
     
        return val * 100 + '%';
      }
    }
  }); // data就是传入的数据。给到F2
  // 图例位置
  pie.legend({
     
    position: 'right',
    itemFormatter: function itemFormatter(val) {
     
      return val + '  ' + map[val];
    }
  });
  pie.tooltip(false);
  pie.coord('polar', {
     
    transposed: true,
    radius: 0.85
  });
  pie.axis(false);
  pie.interval().position('a*percent').color('name', ['#2d8cf0', '#19be6b','#ff9900','#bbbec4']).adjust('stack').style({
     
    lineWidth: 1,
    stroke: '#fff',
    lineJoin: 'round',
    lineCap: 'round'
  }).animate({
     
    appear: {
     
      duration: 1200,
      easing: 'bounceOut'
    }
  });
  pie.render(); // 执行
};
const app = getApp();
Page({
     

  /**
   * 页面的初始数据
   */
  data: {
     
    optspie: {
     lazyLoad: true},
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
     
    this.getPlanList();
  },
  // 获取数据
  getPlanList() {
     
    wx.showLoading({
     
      title: '数据加载中',
    });
    var options = {
     
      url: '#',
      data:'#'
    };
    app.call.request(options, this, this.sucesssPlanHandelList, this.failFun);
  },
  sucesssPlanHandelList(res){
     
    wx.hideLoading();
    console.log('planHandel',res);
    if(res){
     
      this.setData({
     
        allTaskNum:res.allTaskNum,//任务总数
        completedRate:res.completedRate,//完成率
        oneTimePassRate:res.oneTimePassRate,//合格率
        uncheckTaskNum:res.uncheckTaskNum,//待检查
        processingTaskNum:res.processingTaskNum,//处理中
        circulatingTaskNum:res.circulatingTaskNum,//流转中
        endedTaskNum:res.endedTaskNum,//已结束
        planHandelContent:res,//计划处理情况
      });
      this.firstComponent = this.selectComponent('#pie');
      this.getOptions(res.allTaskNum,res.uncheckTaskNum,res.processingTaskNum,res.circulatingTaskNum,res.endedTaskNum);
    }
  },
  failFun(err){
     
    wx.hideLoading();
    app.toast('数据获取失败');
    console.log('fail', err);
  },
  // 初始化图表,给图表添上数据
  getOptions(a,b,c,d,e){
     
    this.firstComponent.init((canvas, width, height) => {
           
      const chart = new F2.Chart({
     
        el: canvas,
        width,
        height,
        animate: false
      });
      setOption(chart,a,b,c,d,e);
    })
  },
})

把图表转化为图片:f2-canvas.js

// f2-canvas.js
import Renderer from './lib/renderer';
import F2 from './lib/f2';

// 适配小程序的事件机制
F2.Util.addEventListener = function (source, type, listener) {
     
  source.addListener(type, listener);
};

F2.Util.removeEventListener = function (source, type, listener) {
     
  source.removeListener(type, listener);
};

F2.Util.createEvent = function (event, chart) {
     
  const type = event.type;
  let x = 0;
  let y = 0;
  const touches = event.touches;
  if (touches && touches.length > 0) {
     
    x = touches[0].x;
    y = touches[0].y;
  }

  return {
     
    type,
    chart,
    x,
    y
  };
};

Component({
     
  /**
   * 组件的属性列表
   */
  properties: {
     
    pieSelect: {
     
      type: String,
      value: 'f2-canvas'
    },
    canvasId: {
     
      type: String,
      value: 'canvas-id'
    },
    opts: {
     
      type: Object
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
     

  },

  ready: function () {
     
    if (!this.data.opts) {
     
      console.warn('组件需绑定 opts 变量,例: +
        'canvas-id="mychart-bar" opts="{
     { opts }}">');
      return;
    }

    if (!this.data.opts.lazyLoad) {
     
      this.init();
    }
  },

  /**
   * 组件的方法列表
   */
  methods: {
     
    init: function (callback) {
     
      const version = wx.version.version.split('.').map(n => parseInt(n, 10));
      const isValid = version[0] > 1 || (version[0] === 1 && version[1] > 9) ||
        (version[0] === 1 && version[1] === 9 && version[2] >= 91);
      if (!isValid) {
     
        console.error('微信基础库版本过低,需大于等于 1.9.91。');
        return;
      }

      const ctx = wx.createCanvasContext(this.data.canvasId, this); // 获取小程序上下文
      const canvas = new Renderer(ctx);
      this.canvas = canvas;
      const query = wx.createSelectorQuery().in(this);
      query.select('.f2-canvas').boundingClientRect(res => {
     
        if (typeof callback === 'function') {
     
          this.chart = callback(canvas, res.width, res.height);
        } else if (this.data.opts && this.data.opts.onInit) {
     
          this.chart = this.data.opts.onInit(canvas, res.width, res.height);
        }
      }).exec();
      var that = this;
      setTimeout(function () {
     
        wx.canvasToTempFilePath({
     
          canvasId: that.data.canvasId,
          success(res) {
     
            console.log('res', res.tempFilePath);
            that.setData({
     
              imgUrl: res.tempFilePath,
            })
          },
          fail(err) {
     
            console.log('err', err);
          }
        }, that)
      }, 1500);
    },
    touchStart(e) {
     
      if (this.canvas) {
     
        this.canvas.emitEvent('touchstart', [e]);
      }
    },
    touchMove(e) {
     
      if (this.canvas) {
     
        this.canvas.emitEvent('touchmove', [e]);
      }
    },
    touchEnd(e) {
     
      if (this.canvas) {
     
        this.canvas.emitEvent('touchend', [e]);
      }
    },
    press(e) {
     
      if (this.canvas) {
     
        this.canvas.emitEvent('press', [e]);
      }
    },
  }
})

f2-canvas.wxml

<image wx:if="{
     {imgUrl}}" src = "{
     {imgUrl}}" style = "width: 100%;height: 100%;"></image>
<canvas
wx:else
class="f2-canvas"
canvas-id="{
     { canvasId }}"
bindinit="init"
bindtouchstart="touchStart"
bindtouchmove="touchMove"
bindtouchend="touchEnd"
bindlongtap="press"
>
</canvas>

最后放一张图片

微信小程序F2饼形图的引入和赋值_第1张图片

你可能感兴趣的:(微信小程序,小程序)