chartjs / Chart.js

Simple HTML5 Charts using the <canvas> tag
https://www.chartjs.org/
MIT License
63.92k stars 11.89k forks source link

Cannot read properties of null (reading 'getContext') #11743

Closed icebob closed 1 month ago

icebob commented 2 months ago

Expected behavior

Handle when the this.canvas is null.

Current behavior

We have a statistics web app with multiple pages with multiple charts and when we change the pages, (if it's as fast as ~1 second) sometimes the chartjs throws an error and after that, all charts disappear and never appear again, just after F5.

https://github.com/chartjs/Chart.js/assets/306521/a65e317a-55bb-4aaa-abd1-d145c397aeb6

This problem does not happen if the animation is turned off.

Reproducible sample

https://codesandbox.io/p/sandbox/vue-chart-3-chart-js-issue-template-forked-f2gkpm

Optional extra steps/info to reproduce

Press the buttons one after the other quickly.

Possible solution

Based on the stack trace, It looks the clearCanvas doesn't handle if the canvas is null

https://github.com/chartjs/Chart.js/blob/1777f959e5f4a80091dd89e798b239b7ba788eb5/src/helpers/helpers.canvas.ts#L135

Context

The error:

helpers.canvas.js:119 Uncaught TypeError: Cannot read properties of null (reading 'getContext')
    at clearCanvas (helpers.canvas.js:119:23)
    at Chart.clear (core.controller.js:268:5)
    at Chart.draw (core.controller.js:718:10)
    at core.animator.js:89:15
    at Map.forEach (<anonymous>)
    at Animator._update (core.animator.js:60:18)
    at core.animator.js:45:12

image

chart.js version

v4.2.1

Browser name and version

Chrome latest

Link to your project

No response