0
2

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 3 years have passed since last update.

グラフを描画する(Svelte × Chart.js)

Posted at

概要

svelteベースのアプリケーションで、chart.jsを使ってグラフを描画してみたのでメモ

依存ライブラリ

ライブラリとそのバージョンです

package.json
{
  ...
  "dependencies": {
    "chart.js": "2.8.0",
    "sirv-cli": "^1.0.0",
    "svelte-spa-router": "^3.1.0"
  }
}

chart.jsは3系が最新のようですが、なぜか2系に下げたらうまく動きました…

実装

<script>
    import {Chart} from "chart.js";

    // 本来API等で取得したものをデータとして使うが、ここではサンプル値を
    let chartData = {
        labels: ["January", "February", "March", "April", "May", "June", "July"],
        datasets: [
            {
                label: "Sample",
                backgroundColor: "rgb(255, 99, 132)",
                borderColor: "rgb(255, 99, 132)",
                data: [0, 10, 5, 2, 20, 30, 45]
            }
        ]
    }
    import { onMount } from 'svelte';

    let chartCanvas;

    function renderChart() {
        let chart = new Chart(chartCanvas, {
            type: "line",
            data: chartData,
            options: {}
        });
    }

    onMount(renderChart)

</script>

<h3>Chart sample.</h3>

<!-- bind:thinでelementを変数に格納できる(document.getElementByIdをしなくて済む) -->
<canvas bind:this={chartCanvas}></canvas>

参考

0
2
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
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?