chartjs / Chart.js

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

Forced re-layout (reflow) when canvas has no fixed width/height #11826

Open joliss opened 6 days ago

joliss commented 6 days ago

Expected behavior

Chart.js should trigger at most one forced reflow (ideally zero) upon initialization.

Current behavior

When the <canvas> has no width and height attributes, Chart.js currently causes multiple forced reflows upon initialization, probably due to interspersed reading and writing of DOM and CSS properties. This causes major slowdowns when there are many charts on a page.

Here's a devtools screenshot, showing the reflows as purple "Layout" bars:

devtools screenshot

Reproducible sample

https://codepen.io/joliss/pen/XWwvrJL

Optional extra steps/info to reproduce

  1. Open the CodePen above
  2. In Chrome devtools's Performance tab, press the ⟳ reload icon
  3. Open the Frame section
  4. In the flame graph, zoom in on the main function call to see the re-layouts

Possible solution

My current workaround is passing canvas.transferControlToOffscreen() instead of canvas to Chart.js, which causes all DOM/CSS writes to be ignored. This does mean that I have to do the sizing logic manually in my own code.

Context

No response

chart.js version

v4.4.3

Browser name and version

Chrome 126.0.6478.127

Link to your project

No response