]> git.ipfire.org Git - thirdparty/Chart.js.git/commitdiff
do not attempt to clear canvas if one does not exist (#11764)
authorArun Philip <dacodedbeat@gmail.com>
Fri, 17 May 2024 12:16:58 +0000 (08:16 -0400)
committerGitHub <noreply@github.com>
Fri, 17 May 2024 12:16:58 +0000 (08:16 -0400)
* 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>
src/helpers/helpers.canvas.ts
test/specs/helpers.canvas.tests.js

index a959d1dea1d2435efc3c9a1fbf22b59dfa756536..f37504c00979dae2a5ae2c35a47bbd5a0a33ae62 100644 (file)
@@ -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();
index ec7a539042a85d8f0792baa3914fdd8986e4543a..ba28e3f78d9095891424ab8859c6a60570b7eb4d 100644 (file)
@@ -21,6 +21,21 @@ 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 createAndClearChart() {
+        var chart = acquireChart({}, {
+          canvas: null
+        });
+        // explicitly set canvas and ctx to null since setting it in acquireChart doesn't do anything
+        chart.canvas = null;
+        chart.ctx = null;
+
+        helpers.clearCanvas(chart.canvas, chart.ctx);
+      }
+
+      expect(createAndClearChart).not.toThrow();
+    });
   });
 
   describe('isPointInArea', function() {