Home >WeChat Applet >Mini Program Development >WeChat applet drawing pie chart implementation

WeChat applet drawing pie chart implementation

高洛峰
高洛峰Original
2017-02-21 15:48:422775browse

The launch of the WeChat mini program will undoubtedly create another storm in the mobile Internet industry. Some people will question whether mini programs will be popular. I don’t know whether they will be popular. You can understand everything by looking at the number of users on WeChat. Here we will first learn how to implement the drawing function of the WeChat applet.

微信小程序 绘图之饼图实现

Official document: http://www.php.cn/

The idea is to draw the first arc first, then connect it back to the center of the circle, and close it Path, please note that there is no need to connect the line to the starting position. Use fill() to automatically close to the starting point. Comparing the path selection method in Photoshop can help to understand; the second arc is the starting angle of the previous arc, and then returns The center of the circle finally closes the path; the third arc is the sum of the previous two arcs as the starting angle and sweeps the arc of the corresponding proportion; and so on to complete the full circle.

微信小程序 绘图之饼图实现

Layout file

33b6b65e50217e89c5a5c8eaffa79210c2caaf3fc160dd2513ce82f021917f8b

Javascript file

Page({
 onReady:function(){
  // 页面渲染完成
  // 创建上下文
  var context = wx.createContext();
// 画饼图
//  数据源
  var array = [20, 30, 40, 40];
  var colors = ["#ff0000", "#ffff00", "#0000ff", "#00ff00"];
  var total = 0;
//  计算问题
  for (index = 0; index < array.length; index++) {
    total += array[index];
  }
//  定义圆心坐标
  var point = {x: 100, y: 100};
//  定义半径大小
  var radius = 60;

/*  循环遍历所有的pie */
  for (i = 0; i < array.length; i++) {
    context.beginPath();
//    起点弧度
    var start = 0;
    if (i > 0) {
//      计算开始弧度是前几项的总和,即从之前的基础的上继续作画
      for (j = 0; j < i; j++) {
        start += array[j] / total * 2 * Math.PI; 
      }
    }
    console.log("i:" + i);
    console.log("start:" + start);
//   1.先做第一个pie
//    2.画一条弧,并填充成三角饼pie,前2个参数确定圆心,第3参数为半径,第4参数起始旋转弧度数,第5参数本次扫过的弧度数,第6个参数为时针方向-false为顺时针
   context.arc(point.x, point.y, radius, start, array[i] / total * 2 * Math.PI, false);
//   3.连线回圆心
   context.lineTo(point.x, point.y);
//   4.填充样式
   context.setFillStyle(colors[i]);
//   5.填充动作
   context.fill();
   context.closePath();
  }

  wx.drawCanvas({
    canvasId: &#39;canvas2&#39;,
    actions: context.getActions()
  });
 }
})

Thank you for reading, I hope it can help everyone, thank you for your support of this site!

For more articles related to WeChat applet pie chart implementation, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn