vue3 chart.js 項目名ラベル名を表示する

項目名を表示しておきたいよね。
そんなときは



参考
https://chartjs-plugin-datalabels.netlify.app/guide/getting-started.html#installation
https://blog.imind.jp/entry/2019/07/19/210646

![aaa.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/31338/9ee78fbb-a3c7-1fac-4027-43b254626dfc.png)



# インスコ♡

```
npm install chartjs-plugin-datalabels --save
```


```hoge.vue
<template>
    <div>
        <div>
            <PieChart :chartData="pieData" />
        </div>
        <el-button @click="saveCanvas"  type="danger">グラフを画像化して保存</el-button>
    </div>
</template>

<script>

    import { Chart, registerables } from "chart.js";
    import ChartDataLabels from 'chartjs-plugin-datalabels';
    import { PieChart, LineChart } from "vue-chart-3";

    Chart.register(
        {
            id: 'customPluginName',
            beforeDraw: function(c){
                var ctx = c.ctx;
                ctx.fillStyle = "#ffffff";
                ctx.fillRect(0, 0, ctx.canvas.width,ctx.canvas.height);
                ctx.save();
            }
        }
    );


    Chart.register(ChartDataLabels);
    Chart.defaults.set('plugins.datalabels', {
        color: '#FFFFFF',
        font: {
            weight: 'bold',
            size: 20,
        },
        formatter: (value, ctx) => {
            let label = ctx.chart.data.labels[ctx.dataIndex];
            return label + '\n' + value + '%';
        }
    });

    Chart.register(...registerables);

    export default {

        components: {
            PieChart,
            LineChart,
        },


        // mixins: [reactiveProp],
        props: ['options'],

        //computed に指定すること！！
        computed: {
            pieData() {
                return {

                    labels: ["Red", "Blue", "Yellow"],
                    datasets: [
                        {
                            label: "My First Dataset",
                            data: [300, 50, 100],
                            backgroundColor: [
                                "rgb(255, 99, 132)",
                                "rgb(54, 162, 235)",
                                "rgb(255, 205, 86)",
                            ],
                            hoverOffset: 4,
                        },
                    ],
                };
            },
        },

        data(){
            return {
            }
        },

        mounted () {

        },

        created(){
        },

        methods: {

            // グラフを 画像にして保存
            saveCanvas(){
                var canvas = document.getElementsByTagName('canvas')[0].toDataURL();
                canvas = canvas.replace(/^data:image\/png;base64,/, '');

                let dataform = new FormData();
                dataform.append('canvas',canvas);

                axios.post('/hoges/upload/', dataform).then(e => {

                    console.log("成功");
                }).catch((error) => {
                    console.log("エラー");
                });

            },

        },
    }

</script>
```


# ウォーターマークを入れる

著作権的な透かし

afterDrawを指定するだけ。

```hoge.js
Chart.register(
    {
        id: 'customPluginName',
        beforeDraw: function(c){
            var ctx = c.ctx;
            ctx.fillStyle = "#ffffff";
            ctx.fillRect(0, 0, ctx.canvas.width,ctx.canvas.height);
            ctx.save();
        },
        afterDraw: (chart) => {
            const image = new Image();
            image.src = 'https://wickedev.com/wp-content/uploads/2020/08/logo-dark-alt.png';
            if (image.complete) {
                const image_height = 82; // Or you can use image.naturalHeight;
                const image_width = 125; // Or you can use image.naturalWidth;
                const ctx = chart.ctx;
                const x = chart.chartArea.width - image_width;
                const y = chart.chartArea.height - image_height;
                ctx.globalAlpha = 0.35;
                ctx.drawImage(image, x, y, image_width, image_height);
                ctx.globalAlpha = 1;
            } else {
                image.onload = () => chart.draw();
            }
        }
    }
);
```



# 余白paddingをつける

```hoge.js
<template>
    <div>
        <div>
            <PieChart :chartData="pieData" :styles="myStyles" :options="options" />
        </div>
        <el-button @click="saveCanvas"  type="danger">グラフを画像化して保存</el-button>
    </div>
</template>

<script>

import { Chart, registerables } from "chart.js";
import ChartDataLabels from 'chartjs-plugin-datalabels';
import { PieChart, LineChart } from "vue-chart-3";

Chart.register(
    {
        id: 'customPluginName',
        beforeDraw: function(c){
            var ctx = c.ctx;
            ctx.fillStyle = "#ffffff";
            ctx.fillRect(0, 0, ctx.canvas.width,ctx.canvas.height);
            ctx.save();
        },
        afterDraw: (chart) => {
            const image = new Image();
            image.src = '/img/logo.png';
            if (image.complete) {
                const image_height = 32; // Or you can use image.naturalHeight;
                const image_width = 103; // Or you can use image.naturalWidth;
                const ctx = chart.ctx;
                const x = chart.chartArea.width - image_width;
                const y = chart.chartArea.height - image_height;
                ctx.globalAlpha = 0.35;
                ctx.drawImage(image, x, y, image_width, image_height);
                ctx.globalAlpha = 1;
            } else {
                image.onload = () => chart.draw();
            }
        }
    }
);


Chart.register(ChartDataLabels);
Chart.defaults.set('plugins.datalabels', {
    color: '#FFFFFF',
    font: {
        weight: 'bold',
        size: 20,
    },
    formatter: (value, ctx) => {
        let label = ctx.chart.data.labels[ctx.dataIndex];
        return label + '\n' + value + '%';
    }
});



Chart.register(...registerables);

export default {

    components: {
        PieChart,
        LineChart,
    },


    // mixins: [reactiveProp],
    // props: ['options'],



    data(){
        return {
            height:300,
            options:{
                layout: {
                    padding: {
                        left: 15,
                        right: 15,
                        top: 15,
                        bottom: 15
                    }
                },
                responsive: true,
                plugins: {
                    legend: {
                        position: false//タイトルを無しにする
                    },
                    title: {
                        display: true,
                        text: 'これがグラフのタイトル',
                    },
                },
            }
        }
    },

    //computed に指定すること！！
    computed: {
        pieData() {
            return {

                labels: ["女性", "男性"],
                datasets: [
                    {
                        label: "My First Dataset",
                        data: [300, 50],
                        backgroundColor: [
                            "rgb(255, 99, 132)",
                            "rgb(54, 162, 235)",
                        ],
                        hoverOffset: 4,
                    },
                ],
            };
        },
        myStyles(){
            return{
                height: `${this.height}px`,
                position:'relative'
            }
        }
    },

    mounted () {

    },

    created(){
    },

    methods: {

        // グラフを 画像にして保存
        saveCanvas(){
            var canvas = document.getElementsByTagName('canvas')[0].toDataURL();
            canvas = canvas.replace(/^data:image\/png;base64,/, '');

            let dataform = new FormData();
            dataform.append('canvas',canvas);

            axios.post('/hoges/upload/', dataform).then(e => {

                console.log("成功");
            }).catch((error) => {
                console.log("エラー");
            });

        },

    },
}

</script>


```