From 6666cbd5d504149531719bd1fed24a848fafce2e Mon Sep 17 00:00:00 2001 From: Arun Philip Date: Tue, 7 May 2024 18:04:05 -0400 Subject: [PATCH] do not attempt to clear canvas if one does not exist --- src/helpers/helpers.canvas.ts | 6 +++++- test/specs/helpers.canvas.tests.js | 10 ++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/src/helpers/helpers.canvas.ts b/src/helpers/helpers.canvas.ts index a959d1dea1d..f37504c0097 100644 --- a/src/helpers/helpers.canvas.ts +++ b/src/helpers/helpers.canvas.ts @@ -131,7 +131,11 @@ export function _alignPixel(chart: Chart, pixel: number, width: number) { /** * Clears the entire canvas. */ -export function clearCanvas(canvas: HTMLCanvasElement, ctx?: CanvasRenderingContext2D) { +export function clearCanvas(canvas?: HTMLCanvasElement, ctx?: CanvasRenderingContext2D) { + if (!ctx && !canvas) { + return; + } + ctx = ctx || canvas.getContext('2d'); ctx.save(); diff --git a/test/specs/helpers.canvas.tests.js b/test/specs/helpers.canvas.tests.js index ec7a539042a..60f1b1f8700 100644 --- a/test/specs/helpers.canvas.tests.js +++ b/test/specs/helpers.canvas.tests.js @@ -21,6 +21,16 @@ describe('Chart.helpers.canvas', function() { expect(chart.ctx.clearRect.calls.first().object).toBe(chart.ctx); expect(chart.ctx.clearRect.calls.first().args).toEqual([0, 0, 150, 245]); }); + + it('should not throw error when chart is null', function() { + function createChart() { + return acquireChart({}, { + canvas: null + }); + } + + expect(createChart).not.toThrow(); + }); }); describe('isPointInArea', function() {