diff --git a/src/chart/bar/BarView.ts b/src/chart/bar/BarView.ts index ba2be19ead..98a32bfe40 100644 --- a/src/chart/bar/BarView.ts +++ b/src/chart/bar/BarView.ts @@ -320,12 +320,14 @@ class BarView extends ChartView { } if (drawBackground) { - let bgEl: Rect | Sector; - if (oldBgEls.length === 0) { - bgEl = createBackground(oldIndex); + // The old item may have had no background (`showBackground` was + // off, or it had no layout). Then create one for the new index; + // the old index may not exist in the new data. + let bgEl = oldBgEls && oldBgEls[oldIndex]; + if (!bgEl) { + bgEl = createBackground(newIndex); } else { - bgEl = oldBgEls[oldIndex]; bgEl.useStyle(backgroundModel.getItemStyle()); // Only cartesian2d support borderRadius. if (coord.type === 'cartesian2d') { @@ -336,9 +338,11 @@ class BarView extends ChartView { } bgEls[newIndex] = bgEl; } - const bgLayout = getLayout[coord.type](data, newIndex); - const shape = createBackgroundShape(isHorizontalOrRadial, bgLayout, coord); - updateProps(bgEl, { shape }, animationModel, newIndex); + const bgLayout = bgEl && getLayout[coord.type](data, newIndex); + if (bgLayout) { + const shape = createBackgroundShape(isHorizontalOrRadial, bgLayout, coord); + updateProps(bgEl, { shape }, animationModel, newIndex); + } } let el = oldData.getItemGraphicEl(oldIndex) as BarPossiblePath; diff --git a/test/ut/spec/series/bar.test.ts b/test/ut/spec/series/bar.test.ts index 73e703d2d9..40e2d3132f 100644 --- a/test/ut/spec/series/bar.test.ts +++ b/test/ut/spec/series/bar.test.ts @@ -62,4 +62,48 @@ describe('bar', function () { } }); + it('draws a background for every bar when showBackground is turned on with fewer bars', function () { + const chart = createChart({width: 400, height: 300}); + const sales: Record = { Apples: 42, Bananas: 75, Cherries: 30, Dates: 88, Figs: 61 }; + + function makeOption(top3: boolean) { + let names = Object.keys(sales); + if (top3) { + names = names.sort((a, b) => sales[b] - sales[a]).slice(0, 3); + } + return { + animation: false, + xAxis: { type: 'category', data: names }, + yAxis: { max: 100 }, + series: [{ + type: 'bar', + showBackground: top3, + data: names.map(name => sales[name]) + }] + }; + } + + function backgroundCount() { + const view = (chart as any)._chartsViews[0]; + return view._backgroundGroup ? view._backgroundGroup.childCount() : 0; + } + + try { + chart.setOption(makeOption(false)); + expect(backgroundCount()).toBe(0); + + expect(() => chart.setOption(makeOption(true))).not.toThrow(); + + const data = (chart as any).getModel().getSeriesByIndex(0).getData(); + expect(data.count()).toBe(3); + expect(backgroundCount()).toBe(3); + for (let i = 0; i < data.count(); i++) { + expect(data.getItemGraphicEl(i)).toBeTruthy(); + } + } + finally { + chart.dispose(); + } + }); + });