| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116 |
- import { mergeDeep } from "@vci/helper/src/object";
- import * as echarts from "echarts";
- import { clearScheduledTasks } from "@vci/helper/src/browser";
- import { viewport } from "../../../../other/adapt";
- import EventDispatcher from "@vci/helper/src/EventDispatcher";
- /**
- * 图表组件
- */
- export default class Chart extends EventDispatcher {
- #proportion;
- constructor(option) {
- super();
- this.option = mergeDeep({
- el: null,
- enableClearBeforeRender: false
- }, option);
- this.init();
- }
- init() {
- this.isChart = true;
- this.el = this.option.el;
- this.inter = {};
- this.initEc();
- this.initEcOption();
- }
- initEcOption(ecOption) {
- if(!ecOption) throw new Error("请设置初始化图表[echarts]配置");
- this.ecOption = ecOption;
- }
- initEc() {
- this.ec = echarts.init(this.el);
- this.#updateProportion();
- this.#addAdapt();
- }
- #setData(data) {
- this._data = data;
- }
- getData() {
- return this._data;
- }
- #setRenderOption(renderOption) {
- this._renderOption = renderOption;
- }
- getRenderOption() {
- return this._renderOption;
- }
- render(data, renderOption) {
- this.#setData(data);
- this.#setRenderOption(renderOption);
- this.option.enableClearBeforeRender && this.ec.clear();
- this.updateEcOption(this.ecOption, data, renderOption);
- this.ec.setOption(this.ecOption);
- }
- // eslint-disable-next-line no-unused-vars
- updateEcOption(ecOption, data, renderOption) {
- throw new Error("请实现渲染前数据配置函数 updateEcOption)");
- }
- #updateProportion() {
- this.#proportion = {
- width: window.innerWidth / viewport.width,
- height: window.innerHeight / viewport.height
- };
- }
- w(px) {
- return px * this.#proportion.width;
- }
- h(hpx) {
- return hpx * this.#proportion.height;
- }
- #addAdapt() {
- this.#removeAdapt();
- this._resize = this.resize.bind(this);
- window.addEventListener("resize", this._resize);
- }
- #removeAdapt() {
- if(this._resize) {
- window.removeEventListener("resize", this._resize);
- delete this._resize;
- }
- }
- resize() {
- clearTimeout(this.inter.resize);
- this.inter.resize = setTimeout(() => {
- this.#updateProportion();
- this.initEcOption();
- this.dispatchEvent("beforeResize");
- this.ec && this.ec.resize();
- this.render(this._data, this._renderOption);
- this.dispatchEvent("afterResize");
- }, 100);
- }
- destroy() {
- this.#removeAdapt();
- clearScheduledTasks(this.inter);
- this.ec && this.ec.dispose();
- }
- }
|