BarView.ts 25.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements.  See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership.  The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License.  You may obtain a copy of the License at
*
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied.  See the License for the
* specific language governing permissions and limitations
* under the License.
*/

S
sushuang 已提交
20
import {__DEV__} from '../../config';
S
sushuang 已提交
21
import * as zrUtil from 'zrender/src/core/util';
S
sushuang 已提交
22
import * as graphic from '../../util/graphic';
S
sushuang 已提交
23
import {setLabel} from './helper';
24 25
import {getBarItemStyle} from './barItemStyle';
import Path, { PathProps } from 'zrender/src/graphic/Path';
26
import Group from 'zrender/src/container/Group';
27
import {throttle} from '../../util/throttle';
28
import {createClipPath} from '../helper/createClipPathFromCoordSys';
29
import Sausage from '../../util/shape/sausage';
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
import ChartView from '../../view/Chart';
import List from '../../data/List';
import GlobalModel from '../../model/Global';
import ExtensionAPI from '../../ExtensionAPI';
import { StageHandlerProgressParams, ECElement, ZRElementEvent } from '../../util/types';
import BarSeriesModel, { BarSeriesOption, BarDataItemOption } from './BarSeries';
import type Axis2D from '../../coord/cartesian/Axis2D';
import type Cartesian2D from '../../coord/cartesian/Cartesian2D';
import type { RectLike } from 'zrender/src/core/BoundingRect';
import type Model from '../../model/Model';

const BAR_BORDER_WIDTH_QUERY = ['itemStyle', 'borderWidth'] as const;
const _eventPos = [0, 0];

const mathMax = Math.max;
const mathMin = Math.min;

type CoordSysOfBar = BarSeriesModel['coordinateSystem'];
type RectShape = graphic.Rect['shape']
type SectorShape = graphic.Sector['shape']

type SectorLayout = SectorShape;
type RectLayout = RectShape;

P
pissang 已提交
54 55
type BarPossiblePath = graphic.Sector | graphic.Rect | Sausage

56 57 58
function isCartesian2D(coord: CoordSysOfBar): coord is Cartesian2D {
    return coord.type === 'cartesian2d';
}
L
lang 已提交
59

60 61 62
function getClipArea(coord: CoordSysOfBar, data: List) {
    if (isCartesian2D(coord)) {
        var coordSysClipArea = coord.getArea && coord.getArea();
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
        var baseAxis = coord.getBaseAxis();
        // When boundaryGap is false or using time axis. bar may exceed the grid.
        // We should not clip this part.
        // See test/bar2.html
        if (baseAxis.type !== 'category' || !baseAxis.onBand) {
            var expandWidth = data.getLayout('bandWidth');
            if (baseAxis.isHorizontal()) {
                coordSysClipArea.x -= expandWidth;
                coordSysClipArea.width += expandWidth * 2;
            }
            else {
                coordSysClipArea.y -= expandWidth;
                coordSysClipArea.height += expandWidth * 2;
            }
        }
    }

    return coordSysClipArea;
}

L
lang 已提交
83

84 85 86 87 88 89 90 91 92 93 94
class BarView extends ChartView {
    static type = 'bar' as const
    type = BarView.type

    _data: List

    _isLargeDraw: boolean

    _backgroundGroup: graphic.Group

    _backgroundEls: (graphic.Rect | graphic.Sector)[]
L
lang 已提交
95

96
    render(seriesModel: BarSeriesModel, ecModel: GlobalModel, api: ExtensionAPI) {
97 98
        this._updateDrawMode(seriesModel);

S
sushuang 已提交
99
        var coordinateSystemType = seriesModel.get('coordinateSystem');
L
lang 已提交
100

S
sushuang 已提交
101 102 103
        if (coordinateSystemType === 'cartesian2d'
            || coordinateSystemType === 'polar'
        ) {
104 105 106
            this._isLargeDraw
                ? this._renderLarge(seriesModel, ecModel, api)
                : this._renderNormal(seriesModel, ecModel, api);
S
sushuang 已提交
107 108 109 110
        }
        else if (__DEV__) {
            console.warn('Only cartesian2d and polar supported for bar.');
        }
L
lang 已提交
111

S
sushuang 已提交
112
        return this.group;
113
    }
L
lang 已提交
114

115
    incrementalPrepareRender(seriesModel: BarSeriesModel) {
116 117
        this._clear();
        this._updateDrawMode(seriesModel);
118
    }
119

120 121
    incrementalRender(
        params: StageHandlerProgressParams, seriesModel: BarSeriesModel) {
122 123
        // Do not support progressive in normal mode.
        this._incrementalRenderLarge(params, seriesModel);
124
    }
125

126
    _updateDrawMode(seriesModel: BarSeriesModel) {
127
        var isLargeDraw = seriesModel.pipelineContext.large;
128
        if (this._isLargeDraw == null || isLargeDraw !== this._isLargeDraw) {
129 130 131
            this._isLargeDraw = isLargeDraw;
            this._clear();
        }
132
    }
L
lang 已提交
133

134
    _renderNormal(seriesModel: BarSeriesModel, ecModel: GlobalModel, api: ExtensionAPI) {
S
sushuang 已提交
135 136 137
        var group = this.group;
        var data = seriesModel.getData();
        var oldData = this._data;
1
100pah 已提交
138

S
sushuang 已提交
139 140
        var coord = seriesModel.coordinateSystem;
        var baseAxis = coord.getBaseAxis();
141
        var isHorizontalOrRadial: boolean;
L
lang 已提交
142

S
sushuang 已提交
143
        if (coord.type === 'cartesian2d') {
144
            isHorizontalOrRadial = (baseAxis as Axis2D).isHorizontal();
S
sushuang 已提交
145 146 147 148
        }
        else if (coord.type === 'polar') {
            isHorizontalOrRadial = baseAxis.dim === 'angle';
        }
O
Ovilia 已提交
149

S
sushuang 已提交
150
        var animationModel = seriesModel.isAnimationEnabled() ? seriesModel : null;
O
Ovilia 已提交
151

152
        var needsClip = seriesModel.get('clip', true);
153
        var coordSysClipArea = getClipArea(coord, data);
154 155 156 157 158
        // If there is clipPath created in large mode. Remove it.
        group.removeClipPath();
        // We don't use clipPath in normal mode because we needs a perfect animation
        // And don't want the label are clipped.

O
Ovilia 已提交
159 160
        var roundCap = seriesModel.get('roundCap', true);

161 162 163
        var drawBackground = seriesModel.get('showBackground', true);
        var backgroundModel = seriesModel.getModel('backgroundStyle');

164 165
        var bgEls: BarView['_backgroundEls'] = [];
        var oldBgEls = this._backgroundEls;
166

S
sushuang 已提交
167 168
        data.diff(oldData)
            .add(function (dataIndex) {
169 170 171 172
                var itemModel = data.getItemModel(dataIndex);
                var layout = getLayout[coord.type](data, dataIndex, itemModel);

                if (drawBackground) {
173 174 175 176
                    var bgEl = createBackgroundEl(
                        coord, isHorizontalOrRadial, layout
                    );
                    bgEl.useStyle(getBarItemStyle(backgroundModel));
177 178 179
                    bgEls[dataIndex] = bgEl;
                }

S
sushuang 已提交
180 181 182
                if (!data.hasValue(dataIndex)) {
                    return;
                }
183

P
pissang 已提交
184 185 186 187 188 189 190 191 192 193
                if (needsClip) {
                    // Clip will modify the layout params.
                    // And return a boolean to determine if the shape are fully clipped.
                    var isClipped = clip[coord.type](coordSysClipArea, layout);
                    if (isClipped) {
                        group.remove(el);
                        return;
                    }
                }

S
sushuang 已提交
194
                var el = elementCreator[coord.type](
195
                    dataIndex, layout, isHorizontalOrRadial, animationModel, false, roundCap
S
sushuang 已提交
196 197 198 199 200 201 202 203 204 205
                );
                data.setItemGraphicEl(dataIndex, el);
                group.add(el);

                updateStyle(
                    el, data, dataIndex, itemModel, layout,
                    seriesModel, isHorizontalOrRadial, coord.type === 'polar'
                );
            })
            .update(function (newIndex, oldIndex) {
206 207
                var itemModel = data.getItemModel(newIndex);
                var layout = getLayout[coord.type](data, newIndex, itemModel);
S
sushuang 已提交
208

209 210
                if (drawBackground) {
                    var bgEl = oldBgEls[oldIndex];
211
                    bgEl.useStyle(getBarItemStyle(backgroundModel));
212 213 214
                    bgEls[newIndex] = bgEl;

                    var shape = createBackgroundShape(isHorizontalOrRadial, layout, coord);
215 216 217
                    graphic.updateProps(
                        bgEl as graphic.Path, { shape: shape }, animationModel, newIndex
                    );
218 219
                }

P
pissang 已提交
220
                var el = oldData.getItemGraphicEl(oldIndex) as BarPossiblePath;
S
sushuang 已提交
221 222 223 224
                if (!data.hasValue(newIndex)) {
                    group.remove(el);
                    return;
                }
L
lang 已提交
225

P
pissang 已提交
226 227 228 229 230 231 232 233
                if (needsClip) {
                    var isClipped = clip[coord.type](coordSysClipArea, layout);
                    if (isClipped) {
                        group.remove(el);
                        return;
                    }
                }

S
sushuang 已提交
234
                if (el) {
235 236 237
                    graphic.updateProps(el as graphic.Path, {
                        shape: layout
                    }, animationModel, newIndex);
S
sushuang 已提交
238 239 240
                }
                else {
                    el = elementCreator[coord.type](
241
                        newIndex, layout, isHorizontalOrRadial, animationModel, true, roundCap
P
pah100 已提交
242
                    );
S
sushuang 已提交
243
                }
1
100pah 已提交
244

S
sushuang 已提交
245 246 247 248 249 250 251 252 253 254 255 256
                data.setItemGraphicEl(newIndex, el);
                // Add back
                group.add(el);

                updateStyle(
                    el, data, newIndex, itemModel, layout,
                    seriesModel, isHorizontalOrRadial, coord.type === 'polar'
                );
            })
            .remove(function (dataIndex) {
                var el = oldData.getItemGraphicEl(dataIndex);
                if (coord.type === 'cartesian2d') {
257
                    el && removeRect(dataIndex, animationModel, el as graphic.Rect);
S
sushuang 已提交
258 259
                }
                else {
260
                    el && removeSector(dataIndex, animationModel, el as graphic.Sector);
S
sushuang 已提交
261 262 263 264
                }
            })
            .execute();

265 266 267 268 269 270 271 272 273
        var bgGroup = this._backgroundGroup || (this._backgroundGroup = new Group());
        bgGroup.removeAll();

        for (var i = 0; i < bgEls.length; ++i) {
            bgGroup.add(bgEls[i]);
        }
        group.add(bgGroup);
        this._backgroundEls = bgEls;

S
sushuang 已提交
274
        this._data = data;
275
    }
S
sushuang 已提交
276

277
    _renderLarge(seriesModel: BarSeriesModel, ecModel: GlobalModel, api: ExtensionAPI) {
278 279
        this._clear();
        createLarge(seriesModel, this.group);
280 281

        // Use clipPath in large mode.
282
        var clipPath = seriesModel.get('clip', true)
283 284 285 286 287 288
            ? createClipPath(seriesModel.coordinateSystem, false, seriesModel)
            : null;
        if (clipPath) {
            this.group.setClipPath(clipPath);
        }
        else {
289
            this.group.removeClipPath();
290
        }
291
    }
292

293
    _incrementalRenderLarge(params: StageHandlerProgressParams, seriesModel: BarSeriesModel) {
294
        this._removeBackground();
295
        createLarge(seriesModel, this.group, true);
296
    }
297

298
    remove(ecModel?: GlobalModel) {
299
        this._clear(ecModel);
300
    }
301

302
    _clear(ecModel?: GlobalModel) {
S
sushuang 已提交
303 304
        var group = this.group;
        var data = this._data;
S
sushuang 已提交
305
        if (ecModel && ecModel.get('animation') && data && !this._isLargeDraw) {
306 307 308
            this._removeBackground();
            this._backgroundEls = [];

309
            data.eachItemGraphicEl(function (el: ECElement & (graphic.Sector | graphic.Rect)) {
S
sushuang 已提交
310
                if (el.type === 'sector') {
311
                    removeSector(el.dataIndex, ecModel, el as (graphic.Sector));
S
sushuang 已提交
312 313
                }
                else {
314
                    removeRect(el.dataIndex, ecModel, el as (graphic.Rect));
S
sushuang 已提交
315 316
                }
            });
L
lang 已提交
317
        }
S
sushuang 已提交
318 319 320
        else {
            group.removeAll();
        }
321
        this._data = null;
322
    }
323

324
    _removeBackground() {
325 326
        this.group.remove(this._backgroundGroup);
        this._backgroundGroup = null;
S
sushuang 已提交
327
    }
328
}
329

330 331 332 333 334 335 336
interface Clipper {
    (coordSysBoundingRect: RectLike, layout: RectLayout | SectorLayout): boolean
}
var clip: {
    [key in 'cartesian2d' | 'polar']: Clipper
} = {
    cartesian2d(coordSysBoundingRect: RectLike, layout: graphic.Rect['shape']) {
P
pissang 已提交
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
        var signWidth = layout.width < 0 ? -1 : 1;
        var signHeight = layout.height < 0 ? -1 : 1;
        // Needs positive width and height
        if (signWidth < 0) {
            layout.x += layout.width;
            layout.width = -layout.width;
        }
        if (signHeight < 0) {
            layout.y += layout.height;
            layout.height = -layout.height;
        }

        var x = mathMax(layout.x, coordSysBoundingRect.x);
        var x2 = mathMin(layout.x + layout.width, coordSysBoundingRect.x + coordSysBoundingRect.width);
        var y = mathMax(layout.y, coordSysBoundingRect.y);
        var y2 = mathMin(layout.y + layout.height, coordSysBoundingRect.y + coordSysBoundingRect.height);

        layout.x = x;
        layout.y = y;
        layout.width = x2 - x;
        layout.height = y2 - y;

359
        var clipped = layout.width < 0 || layout.height < 0;
P
pissang 已提交
360 361 362 363 364 365 366 367 368 369 370 371 372 373

        // Reverse back
        if (signWidth < 0) {
            layout.x += layout.width;
            layout.width = -layout.width;
        }
        if (signHeight < 0) {
            layout.y += layout.height;
            layout.height = -layout.height;
        }

        return clipped;
    },

374
    polar() {
P
pissang 已提交
375 376 377 378
        return false;
    }
};

379 380 381 382
interface ElementCreator {
    (
        dataIndex: number, layout: RectLayout | SectorLayout, isHorizontalOrRadial: boolean,
        animationModel: BarSeriesModel, isUpdate: boolean, roundCap?: boolean
P
pissang 已提交
383
    ): BarPossiblePath
384 385 386 387 388
}

var elementCreator: {
    [key in 'polar' | 'cartesian2d']: ElementCreator
} = {
P
pah100 已提交
389

390 391
    cartesian2d(
        dataIndex, layout: RectLayout, isHorizontal,
S
sushuang 已提交
392 393
        animationModel, isUpdate
    ) {
394 395 396 397 398 399
        var rect = new graphic.Rect({
            shape: zrUtil.extend({}, layout),
            z2: 1
        });

        rect.name = 'item';
S
sushuang 已提交
400 401 402 403

        // Animation
        if (animationModel) {
            var rectShape = rect.shape;
404 405
            var animateProperty = isHorizontal ? 'height' : 'width' as 'width' | 'height';
            var animateTarget = {} as RectShape;
S
sushuang 已提交
406 407 408 409 410 411
            rectShape[animateProperty] = 0;
            animateTarget[animateProperty] = layout[animateProperty];
            graphic[isUpdate ? 'updateProps' : 'initProps'](rect, {
                shape: animateTarget
            }, animationModel, dataIndex);
        }
1
100pah 已提交
412

S
sushuang 已提交
413 414
        return rect;
    },
1
100pah 已提交
415

416 417
    polar(
        dataIndex: number, layout: SectorLayout, isRadial: boolean,
418
        animationModel, isUpdate, roundCap
S
sushuang 已提交
419
    ) {
S
sushuang 已提交
420 421 422 423 424
        // Keep the same logic with bar in catesion: use end value to control
        // direction. Notice that if clockwise is true (by default), the sector
        // will always draw clockwisely, no matter whether endAngle is greater
        // or less than startAngle.
        var clockwise = layout.startAngle < layout.endAngle;
425

O
Ovilia 已提交
426
        var ShapeClass = (!isRadial && roundCap) ? Sausage : graphic.Sector;
427 428

        var sector = new ShapeClass({
429 430
            shape: zrUtil.defaults({clockwise: clockwise}, layout),
            z2: 1
S
sushuang 已提交
431
        });
S
sushuang 已提交
432

433 434
        sector.name = 'item';

S
sushuang 已提交
435 436 437
        // Animation
        if (animationModel) {
            var sectorShape = sector.shape;
438 439
            var animateProperty = isRadial ? 'r' : 'endAngle' as 'r' | 'endAngle';
            var animateTarget = {} as SectorShape;
S
sushuang 已提交
440 441 442 443 444 445
            sectorShape[animateProperty] = isRadial ? 0 : layout.startAngle;
            animateTarget[animateProperty] = layout[animateProperty];
            graphic[isUpdate ? 'updateProps' : 'initProps'](sector, {
                shape: animateTarget
            }, animationModel, dataIndex);
        }
O
Ovilia 已提交
446

S
sushuang 已提交
447 448 449 450
        return sector;
    }
};

451 452 453 454 455
function removeRect(
    dataIndex: number,
    animationModel: BarSeriesModel | GlobalModel,
    el: graphic.Rect
) {
S
sushuang 已提交
456 457 458 459 460
    // Not show text when animating
    el.style.text = null;
    graphic.updateProps(el, {
        shape: {
            width: 0
O
Ovilia 已提交
461
        }
S
sushuang 已提交
462 463 464 465 466
    }, animationModel, dataIndex, function () {
        el.parent && el.parent.remove(el);
    });
}

467 468 469 470 471
function removeSector(
    dataIndex: number,
    animationModel: BarSeriesModel | GlobalModel,
    el: graphic.Sector
) {
S
sushuang 已提交
472 473 474 475 476 477 478 479 480 481 482
    // Not show text when animating
    el.style.text = null;
    graphic.updateProps(el, {
        shape: {
            r: el.shape.r0
        }
    }, animationModel, dataIndex, function () {
        el.parent && el.parent.remove(el);
    });
}

483 484 485 486 487 488 489 490
interface GetLayout {
    (data: List, dataIndex: number, itemModel: Model<BarDataItemOption>): RectLayout | SectorLayout
}
var getLayout: {
    [key in 'cartesian2d' | 'polar']: GetLayout
} = {
    cartesian2d(data, dataIndex, itemModel): RectLayout {
        var layout = data.getItemLayout(dataIndex) as RectLayout;
S
sushuang 已提交
491 492 493 494 495 496 497 498 499 500 501 502 503
        var fixedLineWidth = getLineWidth(itemModel, layout);

        // fix layout with lineWidth
        var signX = layout.width > 0 ? 1 : -1;
        var signY = layout.height > 0 ? 1 : -1;
        return {
            x: layout.x + signX * fixedLineWidth / 2,
            y: layout.y + signY * fixedLineWidth / 2,
            width: layout.width - signX * fixedLineWidth,
            height: layout.height - signY * fixedLineWidth
        };
    },

504
    polar(data, dataIndex, itemModel): SectorLayout {
S
sushuang 已提交
505 506 507 508 509 510 511 512
        var layout = data.getItemLayout(dataIndex);
        return {
            cx: layout.cx,
            cy: layout.cy,
            r0: layout.r0,
            r: layout.r,
            startAngle: layout.startAngle,
            endAngle: layout.endAngle
513
        } as SectorLayout;
1
100pah 已提交
514
    }
S
sushuang 已提交
515 516
};

517
function isZeroOnPolar(layout: SectorLayout) {
518 519 520 521 522
    return layout.startAngle != null
        && layout.endAngle != null
        && layout.startAngle === layout.endAngle;
}

S
sushuang 已提交
523
function updateStyle(
P
pissang 已提交
524
    el: BarPossiblePath,
525 526 527 528 529 530
    data: List, dataIndex: number,
    itemModel: Model<BarDataItemOption>,
    layout: RectLayout | SectorLayout,
    seriesModel: BarSeriesModel,
    isHorizontal: boolean,
    isPolar: boolean
S
sushuang 已提交
531 532 533
) {
    var color = data.getItemVisual(dataIndex, 'color');
    var opacity = data.getItemVisual(dataIndex, 'opacity');
Z
zhangyi 已提交
534
    var stroke = data.getVisual('borderColor');
535
    var itemStyleModel = itemModel.getModel('itemStyle');
536
    var hoverStyle = getBarItemStyle(itemModel.getModel(['emphasis', 'itemStyle']));
S
sushuang 已提交
537 538 539

    if (!isPolar) {
        el.setShape('r', itemStyleModel.get('barBorderRadius') || 0);
O
Ovilia 已提交
540 541
    }

S
sushuang 已提交
542 543
    el.useStyle(zrUtil.defaults(
        {
544 545
            stroke: isZeroOnPolar(layout as SectorLayout) ? 'none' : stroke,
            fill: isZeroOnPolar(layout as SectorLayout) ? 'none' : color,
Z
zhangyi 已提交
546
            opacity: opacity
P
pah100 已提交
547
        },
548
        getBarItemStyle(itemStyleModel)
S
sushuang 已提交
549
    ));
1
100pah 已提交
550

S
sushuang 已提交
551 552
    var cursorStyle = itemModel.getShallow('cursor');
    cursorStyle && el.attr('cursor', cursorStyle);
1
100pah 已提交
553

S
sushuang 已提交
554
    if (!isPolar) {
555 556 557 558
        var labelPositionOutside = isHorizontal
            ? ((layout as RectLayout).height > 0 ? 'bottom' : 'top')
            : ((layout as RectLayout).width > 0 ? 'left' : 'right');

S
sushuang 已提交
559 560 561 562
        setLabel(
            el.style, hoverStyle, itemModel, color,
            seriesModel, dataIndex, labelPositionOutside
        );
1
100pah 已提交
563
    }
564
    if (isZeroOnPolar(layout as SectorLayout)) {
Z
zhangyi 已提交
565 566
        hoverStyle.fill = hoverStyle.stroke = 'none';
    }
S
sushuang 已提交
567 568
    graphic.setHoverStyle(el, hoverStyle);
}
1
tweak  
100pah 已提交
569

S
sushuang 已提交
570
// In case width or height are too small.
571 572 573 574
function getLineWidth(
    itemModel: Model<BarSeriesOption>,
    rawLayout: RectLayout
) {
S
sushuang 已提交
575
    var lineWidth = itemModel.get(BAR_BORDER_WIDTH_QUERY) || 0;
576 577 578 579
    // width or height may be NaN for empty data
    var width = isNaN(rawLayout.width) ? Number.MAX_VALUE : Math.abs(rawLayout.width);
    var height = isNaN(rawLayout.height) ? Number.MAX_VALUE : Math.abs(rawLayout.height);
    return Math.min(lineWidth, width, height);
S
sushuang 已提交
580
}
581

582 583 584 585 586 587 588 589
class LagePathShape {
    points: ArrayLike<number>
}
interface LargePathProps extends PathProps {
    shape?: LagePathShape
}
class LargePath extends Path {
    type = 'largeBar'
590

591
    shape: LagePathShape
592

593 594 595 596
    __startPoint: number[]
    __baseDimIdx: number
    __largeDataIndices: ArrayLike<number>
    __barWidth: number
597

598 599 600
    constructor(opts?: LargePathProps) {
        super(opts, null, new LagePathShape());
    }
601

602
    buildPath(ctx: CanvasRenderingContext2D, shape: LagePathShape) {
603 604
        // Drawing lines is more efficient than drawing
        // a whole line or drawing rects.
605 606 607
        const points = shape.points;
        const startPoint = this.__startPoint;
        const baseDimIdx = this.__baseDimIdx;
608 609

        for (var i = 0; i < points.length; i += 2) {
610
            startPoint[baseDimIdx] = points[i + baseDimIdx];
611 612 613 614
            ctx.moveTo(startPoint[0], startPoint[1]);
            ctx.lineTo(points[i], points[i + 1]);
        }
    }
615
}
616

617 618 619 620 621
function createLarge(
    seriesModel: BarSeriesModel,
    group: Group,
    incremental?: boolean
) {
622 623 624
    // TODO support polar
    var data = seriesModel.getData();
    var startPoint = [];
625 626
    var baseDimIdx = data.getLayout('valueAxisHorizontal') ? 1 : 0;
    startPoint[1 - baseDimIdx] = data.getLayout('valueAxisStart');
627

628 629 630 631 632 633 634
    var largeDataIndices = data.getLayout('largeDataIndices');
    var barWidth = data.getLayout('barWidth');

    var backgroundModel = seriesModel.getModel('backgroundStyle');
    var drawBackground = seriesModel.get('showBackground', true);

    if (drawBackground) {
635 636
        const points = data.getLayout('largeBackgroundPoints');
        const backgroundStartPoint: number[] = [];
637 638
        backgroundStartPoint[1 - baseDimIdx] = data.getLayout('backgroundStart');

639
        const bgEl = new LargePath({
640 641 642 643 644
            shape: {points: points},
            incremental: !!incremental,
            silent: true,
            z2: 0
        });
645 646 647 648
        bgEl.__startPoint = backgroundStartPoint;
        bgEl.__baseDimIdx = baseDimIdx;
        bgEl.__largeDataIndices = largeDataIndices;
        bgEl.__barWidth = barWidth;
649 650 651 652
        setLargeBackgroundStyle(bgEl, backgroundModel, data);
        group.add(bgEl);
    }

653 654
    var el = new LargePath({
        shape: {points: data.getLayout('largePoints')},
655
        incremental: !!incremental
656
    });
657 658 659 660
    el.__startPoint = startPoint;
    el.__baseDimIdx = baseDimIdx;
    el.__largeDataIndices = largeDataIndices;
    el.__barWidth = barWidth;
661 662
    group.add(el);
    setLargeStyle(el, seriesModel, data);
663 664

    // Enable tooltip and user mouse/touch event handlers.
665
    (el as ECElement).seriesIndex = seriesModel.seriesIndex;
666 667 668 669 670 671 672 673

    if (!seriesModel.get('silent')) {
        el.on('mousedown', largePathUpdateDataIndex);
        el.on('mousemove', largePathUpdateDataIndex);
    }
}

// Use throttle to avoid frequently traverse to find dataIndex.
674
var largePathUpdateDataIndex = throttle(function (this: LargePath, event: ZRElementEvent) {
675 676
    var largePath = this;
    var dataIndex = largePathFindDataIndex(largePath, event.offsetX, event.offsetY);
677
    (largePath as ECElement).dataIndex = dataIndex >= 0 ? dataIndex : null;
678 679
}, 30, false);

680
function largePathFindDataIndex(largePath: LargePath, x: number, y: number) {
681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711
    var baseDimIdx = largePath.__baseDimIdx;
    var valueDimIdx = 1 - baseDimIdx;
    var points = largePath.shape.points;
    var largeDataIndices = largePath.__largeDataIndices;
    var barWidthHalf = Math.abs(largePath.__barWidth / 2);
    var startValueVal = largePath.__startPoint[valueDimIdx];

    _eventPos[0] = x;
    _eventPos[1] = y;
    var pointerBaseVal = _eventPos[baseDimIdx];
    var pointerValueVal = _eventPos[1 - baseDimIdx];
    var baseLowerBound = pointerBaseVal - barWidthHalf;
    var baseUpperBound = pointerBaseVal + barWidthHalf;

    for (var i = 0, len = points.length / 2; i < len; i++) {
        var ii = i * 2;
        var barBaseVal = points[ii + baseDimIdx];
        var barValueVal = points[ii + valueDimIdx];
        if (
            barBaseVal >= baseLowerBound && barBaseVal <= baseUpperBound
            && (
                startValueVal <= barValueVal
                    ? (pointerValueVal >= startValueVal && pointerValueVal <= barValueVal)
                    : (pointerValueVal >= barValueVal && pointerValueVal <= startValueVal)
            )
        ) {
            return largeDataIndices[i];
        }
    }

    return -1;
712 713
}

714 715 716 717 718
function setLargeStyle(
    el: LargePath,
    seriesModel: BarSeriesModel,
    data: List
) {
719 720 721 722 723 724 725 726 727
    var borderColor = data.getVisual('borderColor') || data.getVisual('color');
    var itemStyle = seriesModel.getModel('itemStyle').getItemStyle(['color', 'borderColor']);

    el.useStyle(itemStyle);
    el.style.fill = null;
    el.style.stroke = borderColor;
    el.style.lineWidth = data.getLayout('barWidth');
}

728 729 730 731 732
function setLargeBackgroundStyle(
    el: LargePath,
    backgroundModel: Model<BarSeriesOption['backgroundStyle']>,
    data: List
) {
733 734 735 736 737 738
    var borderColor = backgroundModel.get('borderColor') || backgroundModel.get('color');
    var itemStyle = backgroundModel.getItemStyle(['color', 'borderColor']);

    el.useStyle(itemStyle);
    el.style.fill = null;
    el.style.stroke = borderColor;
739
    el.style.lineWidth = data.getLayout('barWidth') as number;
740 741
}

742 743 744 745 746 747 748 749 750 751 752 753 754 755
function createBackgroundShape(
    isHorizontalOrRadial: boolean,
    layout: SectorLayout | RectLayout,
    coord: CoordSysOfBar
): SectorShape | RectShape {
    if (isCartesian2D(coord)) {
        const rectShape = layout as RectShape;
        const coordLayout = coord.getArea();
        return {
            x: isHorizontalOrRadial ? rectShape.x : coordLayout.x,
            y: isHorizontalOrRadial ? coordLayout.y : rectShape.y,
            width: isHorizontalOrRadial ? rectShape.width : coordLayout.width,
            height: isHorizontalOrRadial ? coordLayout.height : rectShape.height
        } as RectShape;
756 757
    }
    else {
758 759
        const coordLayout = coord.getArea();
        const sectorShape = layout as SectorShape;
760 761 762
        return {
            cx: coordLayout.cx,
            cy: coordLayout.cy,
763 764 765 766 767
            r0: isHorizontalOrRadial ? coordLayout.r0 : sectorShape.r0,
            r: isHorizontalOrRadial ? coordLayout.r : sectorShape.r,
            startAngle: isHorizontalOrRadial ? sectorShape.startAngle : 0,
            endAngle: isHorizontalOrRadial ? sectorShape.endAngle : Math.PI * 2
        } as SectorShape;
768 769 770
    }
}

771 772 773 774 775
function createBackgroundEl(
    coord: CoordSysOfBar,
    isHorizontalOrRadial: boolean,
    layout: SectorLayout | RectLayout
): graphic.Rect | graphic.Sector {
776 777
    var ElementClz = coord.type === 'polar' ? graphic.Sector : graphic.Rect;
    return new ElementClz({
778
        shape: createBackgroundShape(isHorizontalOrRadial, layout, coord) as any,
779 780 781 782
        silent: true,
        z2: 0
    });
}
783 784 785 786

ChartView.registerClass(BarView);

export default BarView;