1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

nuxt3,chart.js4系で円グラフ内に文字を表示する

Posted at

chart.js4系で円グラフ内に文字を入れる

いつものようにyarn add

yarn add chart.js vue-chart-3

templateに描画するcomponentを追加
nuxtなのでインポートしなくても自動で読み込み

<template>
  <div class="canvas-area">
    <div>
      <DoughnutChart :chartData="chartData" :options="options" />
    </div>
  </div>
</template>

カスタムプラグインをChartに登録する

<script setup lang="ts">
import { DoughnutChart } from 'vue-chart-3'
import { Chart, registerables, ChartOptions } from 'chart.js'

Chart.register(...registerables)

const chartData = {
  datasets: [
    {
      data: [70, 5],
      backgroundColor: ['#FF5541', '#D2D2D2'],
    },
  ],
}

// ドーナッツの中央に文字を表示する
const customPlugin = {
  id: 'customTextDraw',
  afterDraw(chart: Chart) {
    const ctx = chart.ctx
    const chartArea = chart.chartArea
    const width = chartArea.right - chartArea.left
    const height = chartArea.bottom - chartArea.top
    const fontSize = (height / 184).toFixed(2)
    ctx.font = `${fontSize}em sans-serif`
    ctx.textBaseline = 'middle'

    const text = 'hogehoge率'
    const textX = Math.round((width - ctx.measureText(text).width) / 2)
    const textY = height / 2.4
    ctx.fillStyle = '#333333'
    ctx.fillText(text, textX, textY)

    const text2 = '70%'
    const fontSize2 = (height / 74).toFixed(2)
    ctx.font = `bold ${fontSize2}em sans-serif`
    ctx.fillStyle = '#FF5541'
    ctx.textBaseline = 'middle'
    const textY2 = (height / 4) * 2.5
    ctx.fillText(text2, textX, textY2)
  },
}

Chart.register(customPlugin)

const options = ref<ChartOptions<'doughnut'>>({
  cutout: 80,
  responsive: true,
})
</script>

以上

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?