Skip to content

Commit e7b8fa2

Browse files
do not attempt to clear canvas if one does not exist (#11764)
* do not attempt to clear canvas if one does not exist * update test to explicitly run clearCanvas method to ensure it doesn't throw an error * explicitly set canvas and ctx to null in test since the helper in test code didn't * Update test/specs/helpers.canvas.tests.js --------- Co-authored-by: Jacco van den Berg <jaccoberg2281@gmail.com>
1 parent ca76d73 commit e7b8fa2

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

src/helpers/helpers.canvas.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,11 @@ export function _alignPixel(chart: Chart, pixel: number, width: number) {
131131
/**
132132
* Clears the entire canvas.
133133
*/
134-
export function clearCanvas(canvas: HTMLCanvasElement, ctx?: CanvasRenderingContext2D) {
134+
export function clearCanvas(canvas?: HTMLCanvasElement, ctx?: CanvasRenderingContext2D) {
135+
if (!ctx && !canvas) {
136+
return;
137+
}
138+
135139
ctx = ctx || canvas.getContext('2d');
136140

137141
ctx.save();

test/specs/helpers.canvas.tests.js

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,21 @@ describe('Chart.helpers.canvas', function() {
2121
expect(chart.ctx.clearRect.calls.first().object).toBe(chart.ctx);
2222
expect(chart.ctx.clearRect.calls.first().args).toEqual([0, 0, 150, 245]);
2323
});
24+
25+
it('should not throw error when chart is null', function() {
26+
function createAndClearChart() {
27+
var chart = acquireChart({}, {
28+
canvas: null
29+
});
30+
// explicitly set canvas and ctx to null since setting it in acquireChart doesn't do anything
31+
chart.canvas = null;
32+
chart.ctx = null;
33+
34+
helpers.clearCanvas(chart.canvas, chart.ctx);
35+
}
36+
37+
expect(createAndClearChart).not.toThrow();
38+
});
2439
});
2540

2641
describe('isPointInArea', function() {

0 commit comments

Comments
 (0)