当前位置: 首页>大数据>正文

echarts立体饼图

function mastery(data) {
    var myChart = echarts.init(document.getElementById('mastery'));
    var color = ["#3356d2", "#6a43f3", "#f3a722", "#5de8ec"]
    var data = data
    data.forEach((item, index) => {
        item.itemStyle = {
            color: color[index],
            opacity: 0.6,
        }
    })

    function getParametricEquation(startRatio, endRatio, isSelected, isHovered, k, h) {
        // 计算
        let midRatio = (startRatio + endRatio) / 2;

        let startRadian = startRatio * Math.PI * 2;
        let endRadian = endRatio * Math.PI * 2;
        let midRadian = midRatio * Math.PI * 2;

        // 如果只有一个扇形,则不实现选中效果。
        if (startRatio === 0 && endRatio === 1) {
            isSelected = false;
        }

        // 通过扇形内径/外径的值,换算出辅助参数 k(默认值 1/3)
        k = 1

        // 计算选中效果分别在 x 轴、y 轴方向上的位移(未选中,则位移均为 0)
        let offsetX = isSelected Math.cos(midRadian) * 0.1 : 0;
        let offsetY = isSelected Math.sin(midRadian) * 0.1 : 0;

        // 计算高亮效果的放大比例(未高亮,则比例为 1)
        let hoverRate = isHovered 1.05 : 1;

        // 返回曲面参数方程
        return {
            u: {
                min: -Math.PI,
                max: Math.PI * 3,
                step: Math.PI / 32,
            },

            v: {
                min: 0,
                max: Math.PI * 2,
                step: Math.PI / 20,
            },

            x: function(u, v) {
                if (u < startRadian) {
                    return offsetX + Math.cos(startRadian) * (1 + Math.cos(v) * k) * hoverRate;
                }
                if (u > endRadian) {
                    return offsetX + Math.cos(endRadian) * (1 + Math.cos(v) * k) * hoverRate;
                }
                return offsetX + Math.cos(u) * (1 + Math.cos(v) * k) * hoverRate;
            },

            y: function(u, v) {
                if (u < startRadian) {
                    return offsetY + Math.sin(startRadian) * (1 + Math.cos(v) * k) * hoverRate;
                }
                if (u > endRadian) {
                    return offsetY + Math.sin(endRadian) * (1 + Math.cos(v) * k) * hoverRate;
                }
                return offsetY + Math.sin(u) * (1 + Math.cos(v) * k) * hoverRate;
            },

            z: function(u, v) {
                if (u < -Math.PI * 0.5) {
                    return Math.sin(u);
                }
                if (u > Math.PI * 2.5) {
                    return Math.sin(u) * h * 0.1;
                }
                return Math.sin(v) > 0 1 * h * 0.1 : -1;
            },
        };
    }


    function getPie3D(pieData, internalDiameterRatio) {
        let series = [];
        let sumValue = 0;
        let startValue = 0;
        let endValue = 0;
        let legendData = [];
        let k = typeof internalDiameterRatio !== 'undefined' (1 - internalDiameterRatio) / (1 +
                internalDiameterRatio) : 1 /
            3;

        // 为每一个饼图数据,生成一个 series-surface 配置
        for (let i = 0; i < pieData.length; i++) {
            sumValue += pieData[i].value;

            let seriesItem = {
                name: typeof pieData[i].name === 'undefined' `series${i}` : pieData[i].name,
                value: typeof pieData[i].value === 'undefined' `series${i}` : pieData[i].value,
                type: 'surface',
                parametric: true,
                wireframe: {
                    show: false,
                },
                pieData: pieData[i],
                pieStatus: {
                    selected: false,
                    hovered: false,
                    k: k,
                },
            };

            if (typeof pieData[i].itemStyle != 'undefined') {
                let itemStyle = {};

                typeof pieData[i].itemStyle.color != 'undefined' (itemStyle.color = pieData[i].itemStyle.color) :
                    null;
                typeof pieData[i].itemStyle.opacity != 'undefined' (itemStyle.opacity = pieData[i].itemStyle
                    .opacity) : null;

                seriesItem.itemStyle = itemStyle;
            }
            series.push(seriesItem);
        }
        // 使用上一次遍历时,计算出的数据和 sumValue,调用 getParametricEquation 函数,
        // 向每个 series-surface 传入不同的参数方程 series-surface.parametricEquation,也就是实现每一个扇形。
        for (let i = 0; i < series.length; i++) {
            endValue = startValue + series[i].pieData.value;
            series[i].pieData.startRatio = startValue / sumValue;
            series[i].pieData.endRatio = endValue / sumValue;
            series[i].parametricEquation = getParametricEquation(
                series[i].pieData.startRatio,
                series[i].pieData.endRatio,
                false,
                false,
                k,
                series[i].pieData.value
            );

            startValue = endValue;
            legendData.push(series[i].name);
        }

        // 补充一个透明的圆环,用于支撑高亮功能的近似实现。
        series.push({
            name: 'mouseoutSeries',
            type: 'surface',
            parametric: true,
            wireframe: {
                show: false,
            },
            itemStyle: {
                opacity: 0,
            },
            parametricEquation: {
                u: {
                    min: 0,
                    max: Math.PI * 2,
                    step: Math.PI / 20,
                },
                v: {
                    min: 0,
                    max: Math.PI,
                    step: Math.PI / 20,
                },
                x: function(u, v) {
                    return Math.sin(v) * Math.sin(u) + Math.sin(u);
                },
                y: function(u, v) {
                    return Math.sin(v) * Math.cos(u) + Math.cos(u);
                },
                z: function(u, v) {
                    return Math.cos(v) > 0 0.1 : -0.1;
                },
            },
        }, {
            name: 'pie2d',
            type: 'pie',
            labelLine: {
                length: 30,
                length2: 30,
            },
            startAngle: -30, //起始角度,支持范围[0, 360]。
            clockwise: false, //饼图的扇区是否是顺时针排布。上述这两项配置主要是为了对齐3d的样式
            radius: ['40%', '40%'],
            center: ['50%', '50%'], //指示线的位置
            data: data,
            itemStyle: {
                opacity: 0,
            },
        });

        // 准备待返回的配置项,把准备好的 legendData、series 传入。
        let option = {
            labelLine: {
                show: true,
                lineStyle: {
                    color: '#fff'
                }
            },
            label: {
                show: true,
                position: 'outside',
                formatter: ['{a|{b}}\n{hr|}\n{c|{c}}'].join('\n'),
                rich: {
                    hr: {
                        backgroundColor: "#fff",
                        borderRadius: 5,
                        width: 5,
                        height: 5,
                        padding: [0, -5],
                        opacity: 1,
                    },
                    a: {
                        fontSize: 14,
                        lineHeight: 30,
                        fontWeight: '400',
                        color: '#fff',
                        opacity: 1,
                        padding: [30, 10, 0, 10]
                    },
                    c: {
                        fontSize: 14,
                        fontWeight: '400',
                        color: '#fff',
                        opacity: 1,
                        padding: [5, 10, 10, 10]
                    },
                },

            },
            xAxis3D: {
                min: -1,
                max: 1,
            },
            yAxis3D: {
                min: -1,
                max: 1,
            },
            zAxis3D: {
                min: -1,
                max: 1,
            },
            grid3D: {
                show: false,
                boxHeight: 30,
                viewControl: {
                    //3d效果可以放大、旋转等,请自己去查看官方配置
                    alpha: 40,
                    beta: 40,
                    distance: 500,
                    rotateSensitivity: 0,
                    zoomSensitivity: 0,
                    panSensitivity: 0,
                    autoRotate: false,
                }
            },
            series: series,
        };
        return option;
    }

    option = getPie3D(data, 0.71);
    if (option && typeof option === 'object') {
        myChart.setOption(option)
    }
}
echarts立体饼图,第1张

需引入echarts-gl.min.js
echarts-gl.min.js:

/**
* echarts-gl
* Extension pack of ECharts providing 3d plots and globe visualization
*
* Copyright (c) 2014, echarts-gl
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
*   list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
*   this list of conditions and the following disclaimer in the documentation
*   and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

/**
* @module echarts-gl
* @author Yi Shen(http://github.com/pissang)
*/

// PENDING Use a single canvas as layer or use image element?
var echartsGl = {
  version: '1.1.1',
  dependencies: {
      echarts: '4.1.0',
      claygl: '1.2.1'
  }
};
import echarts from 'echarts/lib/echarts';
import clayVersion from 'claygl/src/version';
import LayerGL from './core/LayerGL';
import backwardCompat from './preprocessor/backwardCompat';
import graphicGL from './util/graphicGL';

// Version checking
var deps = echartsGl.dependencies;
function versionTooOldMsg(name) {
  throw new Error(
      name + ' version is too old, needs ' + deps[name] + ' or higher'
  );
}
function checkVersion(version, name) {
  if ((version.replace('.', '') - 0) < (deps[name].replace('.', '') - 0)) {
      versionTooOldMsg(name);
  }
  // console.log('Loaded ' + name + ', version ' + version);
}
checkVersion(clayVersion, 'claygl');
checkVersion(echarts.version, 'echarts');

function EChartsGL (zr) {
  this._layers = {};

  this._zr = zr;
}

EChartsGL.prototype.update = function (ecModel, api) {
  var self = this;
  var zr = api.getZr();

  if (!zr.getWidth() || !zr.getHeight()) {
      console.warn('Dom has no width or height');
      return;
  }

  function getLayerGL(model) {
      var zlevel;
      // Host on coordinate system.
      if (model.coordinateSystem && model.coordinateSystem.model) {
          zlevel = model.get('zlevel');
      }
      else {
          zlevel = model.get('zlevel');
      }

      var layers = self._layers;
      var layerGL = layers[zlevel];
      if (!layerGL) {
          layerGL = layers[zlevel] = new LayerGL('gl-' + zlevel, zr);

          if (zr.painter.isSingleCanvas()) {
              layerGL.virtual = true;
              // If container is canvas, use image to represent LayerGL
              // FIXME Performance
              var img = new echarts.graphic.Image({
                  z: 1e4,
                  style: {
                      image: layerGL.renderer.canvas
                  },
                  silent: true
              });
              layerGL.__hostImage = img;

              zr.add(img);
          }

          zr.painter.insertLayer(zlevel, layerGL);
      }
      if (layerGL.__hostImage) {
          layerGL.__hostImage.setStyle({
              width: layerGL.renderer.getWidth(),
              height: layerGL.renderer.getHeight()
          });
      }

      return layerGL;
  }

  function setSilent(groupGL, silent) {
      if (groupGL) {
          groupGL.traverse(function (mesh) {
              if (mesh.isRenderable && mesh.isRenderable()) {
                  mesh.ignorePicking = mesh.$ignorePicking != null
                      mesh.$ignorePicking : silent;
              }
          });
      }
  }

  for (var zlevel in this._layers) {
      this._layers[zlevel].removeViewsAll();
  }

  ecModel.eachComponent(function (componentType, componentModel) {
      if (componentType !== 'series') {
          var view = api.getViewOfComponentModel(componentModel);
          var coordSys = componentModel.coordinateSystem;
          // View with __ecgl__ flag is a echarts-gl component.
          if (view.__ecgl__) {
              var viewGL;
              if (coordSys) {
                  if (!coordSys.viewGL) {
                      console.error('Can\'t find viewGL in coordinateSystem of component ' + componentModel.id);
                      return;
                  }
                  viewGL = coordSys.viewGL;
              }
              else {
                  if (!componentModel.viewGL) {
                      console.error('Can\'t find viewGL of component ' + componentModel.id);
                      return;
                  }
                  viewGL = coordSys.viewGL;
              }

              viewGL = coordSys.viewGL;
              var layerGL = getLayerGL(componentModel);

              layerGL.addView(viewGL);

              view.afterRender && view.afterRender(
                  componentModel, ecModel, api, layerGL
              );

              setSilent(view.groupGL, componentModel.get('silent'));
          }
      }
  });

  ecModel.eachSeries(function (seriesModel) {
      var chartView = api.getViewOfSeriesModel(seriesModel);
      var coordSys = seriesModel.coordinateSystem;
      if (chartView.__ecgl__) {
          if ((coordSys && !coordSys.viewGL) && !chartView.viewGL) {
              console.error('Can\'t find viewGL of series ' + chartView.id);
              return;
          }
          var viewGL = (coordSys && coordSys.viewGL) || chartView.viewGL;
          // TODO Check zlevel not same with component of coordinate system ?
          var layerGL = getLayerGL(seriesModel);
          layerGL.addView(viewGL);

          chartView.afterRender && chartView.afterRender(
              seriesModel, ecModel, api, layerGL
          );

          setSilent(chartView.groupGL, seriesModel.get('silent'));
      }
  });
};

// Hack original getRenderedCanvas. Will removed after new echarts released
// TODO
var oldInit = echarts.init;
echarts.init = function () {
  var chart = oldInit.apply(this, arguments);
  chart.getZr().painter.getRenderedCanvas = function (opts) {
      opts = opts || {};
      if (this._singleCanvas) {
          return this._layers[0].dom;
      }

      var canvas = document.createElement('canvas');
      var dpr = opts.pixelRatio || this.dpr;
      canvas.width = this.getWidth() * dpr;
      canvas.height = this.getHeight() * dpr;
      var ctx = canvas.getContext('2d');
      ctx.dpr = dpr;

      ctx.clearRect(0, 0, canvas.width, canvas.height);
      if (opts.backgroundColor) {
          ctx.fillStyle = opts.backgroundColor;
          ctx.fillRect(0, 0, canvas.width, canvas.height);
      }

      var displayList = this.storage.getDisplayList(true);

      var scope = {};
      var zlevel;

      var self = this;
      function findAndDrawOtherLayer(smaller, larger) {
          var zlevelList = self._zlevelList;
          if (smaller == null) {
              smaller = -Infinity;
          }
          var intermediateLayer;
          for (var i = 0; i < zlevelList.length; i++) {
              var z = zlevelList[i];
              var layer = self._layers[z];
              if (!layer.__builtin__ && z > smaller && z < larger) {
                  intermediateLayer = layer;
                  break;
              }
          }
          if (intermediateLayer && intermediateLayer.renderToCanvas) {
              ctx.save();
              intermediateLayer.renderToCanvas(ctx);
              ctx.restore();
          }
      }
      var layer = {
          ctx: ctx
      };
      for (var i = 0; i < displayList.length; i++) {
          var el = displayList[i];

          if (el.zlevel !== zlevel) {
              findAndDrawOtherLayer(zlevel, el.zlevel);
              zlevel = el.zlevel;
          }
          this._doPaintEl(el, layer, true, scope);
      }

      findAndDrawOtherLayer(zlevel, Infinity);

      return canvas;
  };
  return chart;
};


echarts.registerPostUpdate(function (ecModel, api) {
  var zr = api.getZr();

  var egl = zr.__egl = zr.__egl || new EChartsGL(zr);

  egl.update(ecModel, api);
});

echarts.registerPreprocessor(backwardCompat);

echarts.graphicGL = graphicGL;

export default EChartsGL;

https://www.xamrdz.com/bigdata/7gb1994014.html

相关文章: