Responsive Charts

    The following examples do not work:

    • <canvas style="height:40vh; width:80vw">: invalid behavior, the canvas is resized but becomes blurry (example (opens new window))

    Chart.js provides a to enable responsiveness and control the resize behavior of charts by detecting when the canvas display size changes and update the render size accordingly.

    Detecting when the canvas size changes can not be done directly from the canvas element. Chart.js uses its parent container to update the canvas render and display sizes. However, this method requires the container to be relatively positioned and dedicated to the chart canvas only. Responsiveness can then be achieved by setting relative values for the container size (exampleResponsive Charts - 图3 (opens new window)):

    The chart can also be programmatically resized by modifying the container size:

    CSS media queries allow changing styles when printing a page. The CSS applied from these media queries may cause charts to need to resize. However, the resize won’t happen automatically. To support resizing charts when printing, you need to hook the onbeforeprint (opens new window) event and manually trigger resizing of each chart.

    You may also find that, due to complexities in when the browser lays out the document for printing and when resize events are fired, Chart.js is unable to properly resize for the print layout. To work around this, you can pass an explicit size to then use an event to restore the automatic size when done.