victorgarciaesgi / vue-chart-3

📊 A simple wrapper around Chart.js 3 for Vue 2 & 3
https://vue-chart-3.netlify.app/
MIT License
310 stars 112 forks source link

How to create a background color gradient #83

Closed Martijn097 closed 2 years ago

Martijn097 commented 2 years ago

Hello, thanks for this package!

I was wondering if you guys could help me create a gradient background color on a chart. I have not seen an issue with this yet.

Right now it does console log the canvas ref and it does console log the canvasgradient but Im not really sure what Im doing wrong here.

<template>
  <div class="per-hour-graph-wrapper">
    <LineChart v-bind="lineChartProps" ref="lineRef" />
  </div>
</template> 

<script> 
import { ref, onMounted } from "vue";
import { defineComponent } from 'vue';

import { LineChart, useLineChart } from 'vue-chart-3';
import { Chart, registerables } from 'chart.js';

export default defineComponent({
  components: { LineChart },
    setup() {
    Chart.register(...registerables);

    const lineRef = ref(null);
    const gradient = ref(null);

    onMounted(() => {
      const canvas = lineRef.value.canvasRef;
      console.log(canvas);
      const gradient = canvas.getContext('2d').createLinearGradient(0, 0, 0, 400);
      gradient.addColorStop(0, 'rgba(255, 0,0, 0.9)')
      gradient.addColorStop(0.5, 'rgba(255, 0, 0, 0.5)');
      gradient.addColorStop(1, 'rgba(255, 0, 0, 0)');
      console.log(gradient);
    })

    const hours = ["00:00", "01:00", "03:00", "04:00", "05:00", "06:00", "07:00", "08:00", "09:00", "10:00", "11:00", "12:00", "13:00", "14:00", "15:00", "16:00", "17:00", "18:00", "19:00", "20:00", "21:00", "22:00", "23:00"];

    const testData = {
      labels: hours,
      showTooltips: false,
      datasets: [
        {
          label: 'Dataset 1',
          data: [0, 20, 23, 40, 23, 24, 54, 3, 45, 24, 54, 66, 34, 54, 54, 22, 33, 44, 55, 23, 15, 22, 53, 56], 
          borderColor: "#3AAFE3",
          backgroundColor: gradient,
          fill: true,
          hoverBackgroundColor: '#FFFFFF',
        },
      ],
    };

    const { lineChartProps, lineChartRef } = useLineChart({
      chartData: testData,
    });

    return { testData, lineChartProps, lineChartRef, lineRef, gradient };
  },
});

36035c2cb589a23708d6b7427b7bffef

Martijn097 commented 2 years ago

Fixed it.

All you gotta do is add .value.

const gradient = ref('red')

onMounted(() => {
  const canvas = lineRef.value.canvasRef;
  gradient.value = canvas.getContext('2d').createLinearGradient(0, 0, 0, 400);
  gradient.value.addColorStop(0, 'rgba(255, 0,0, 0.9)')
  gradient.value.addColorStop(0.5, 'rgba(255, 0, 0, 0.5)');
  gradient.value.addColorStop(1, 'rgba(255, 0, 0, 0)');
 })

 const testData = computed(() => ({
   datasets: [
     {
       backgroundColor: gradient.value
     }
   ]
 }));