Search code examples
typescriptcanvaschart.jssvelte

How to remove the white space around a chart in chart.js


I have a chart inside a div element, as shown below, that has white space around it. How would I remove the white space there? inspected element chart

I've tried all the answers here: https://stackoverflow.com/questions/41546993/chartjs-is-there-any-way-to-remove-blank-space-around-pie-charts#:~:text=According%20to%20the%20docs%20here,Hope%20this%20helps%20someone! but none of them seem to work with the latest version of chartjs (I am on 4.2.1).

chart code:

import { Chart } from "chart.js/auto"
import { curvePlugin, textPlugin } from "./plugins"

type ChartGauge = typeof Chart

export interface Props {
  // may add more prop vals later
  value: number
}

export const addChart = (node: HTMLElement, params: Props): ChartGauge => {
  const text = textPlugin(params)
  const curve = curvePlugin()
  return new Chart(node, {
    type: "doughnut",
    data: {
      datasets: [
        {
          //label: params.caption,
          data: [params.value, 100 - params.value],
          backgroundColor: ["#056DFF", "#D9D9D9"],
          borderColor: ["rgba(255, 255, 255 ,1)"],
          borderWidth: 0,
        },
      ],
    },
    options: {
      rotation: -90,
      cutout: "85%",
      circumference: 180,
      radius: "50%",
      responsive: false
    },
    plugins: [text, curve],
  })
}

Display code:

  <div>
    <canvas
    id="chart"
    use:addChart={{value}}
    >
    </canvas>
  </div>

Solution

  • Set the radius to a higher value REPL

    options: {
        ...
        radius: "80%",
    },