UNPKG

@antv/g2plot

Version:

G2 Plot, a market of plots built with the Grammar of Graphics'

82 lines 2.9 kB
import { __assign } from "tslib"; import { Group } from '@antv/g'; import * as _ from '@antv/util'; import { VALUE_FIELD, IS_TOTAL } from '../../layer'; function getDefaultCfg() { return { fill: '#fff', fontSize: 12, lineHeight: 12, stroke: 'rgba(0, 0, 0, 0.45)', }; } var DiffLabel = /** @class */ (function () { function DiffLabel(cfg) { this.textAttrs = {}; this.view = cfg.view; this.fields = cfg.fields; this.formatter = cfg.formatter; this.textAttrs = _.mix(getDefaultCfg(), cfg.style); this._init(); } /** 绘制辅助labels */ DiffLabel.prototype.draw = function () { var _this = this; if (!this.view || this.view.destroyed) { return; } var data = _.clone(this.view.get('data')); this.container = this.view.get('frontgroundGroup').addGroup(); var shapes = this.view .get('elements')[0] .getShapes() .filter(function (s) { return s.name === 'interval'; }); var labelsGroup = new Group(); _.each(shapes, function (shape, idx) { if (!shape.get('origin')) return; var _origin = shape.get('origin')._origin; var shapeBox = shape.getBBox(); var values = _origin[VALUE_FIELD]; var diff = values; if (_.isArray(values)) { diff = values[1] - values[0]; } diff = diff > 0 ? "+" + diff : diff; /** is total, total do not need `+` sign */ if (_origin[IS_TOTAL]) { diff = values[0] - values[1]; } var formattedText = diff; if (_this.formatter) { var color = shapes[idx].attr('fill'); formattedText = _this.formatter("" + diff, { _origin: data[idx], color: color }, idx); } var text = labelsGroup.addShape('text', { attrs: __assign({ text: formattedText, textBaseline: 'middle', textAlign: 'center', x: (shapeBox.minX + shapeBox.maxX) / 2, y: (shapeBox.minY + shapeBox.maxY) / 2 }, _this.textAttrs), }); if (text.getBBox().height > shapeBox.height) { text.set('visible', false); } }); this.container.add(labelsGroup); this.view.get('canvas').draw(); }; DiffLabel.prototype.clear = function () { if (this.container) { this.container.clear(); } }; DiffLabel.prototype._init = function () { var _this = this; this.view.on('beforerender', function () { _this.clear(); }); this.view.on('afterrender', function () { _this.draw(); }); }; return DiffLabel; }()); export default DiffLabel; //# sourceMappingURL=diff-label.js.map