(Vue, ChartJS) Create gradient background for chart from child component canvas context

无人久伴 提交于 2020-03-19 03:53:41

问题


I want to give my chart a gradient background color, but I can't access the canvas context as my chart gets rendered in a wrapper component I wrote.

What I want to achieve:

My actual wrapper rather looks like this:

<script>
import { Line, mixins } from "vue-chartjs";
const { reactiveProp } = mixins;

export default {
  extends: Line,
  mixins: [reactiveProp],
  props: ["options"],
  components: {},
  mounted() {
    // this.chartData is created in the mixin
    this.renderChart(this.chartData, this.options);
  }
};
</script>

I'm using my wrapper for different line charts and let it's parent pass down the relevant data - sometimes using the wrapper component several times per page.

All configuration (options, labels, etc.) gets done in the parent component, which uses the wrapper.

Is there a way to get the canvas context from the wrapper to the parent component, which uses the wrapper?

To create the gradient, you need something like this:

this.gradient = this.$refs.canvas
  .getContext("2d")
  .createLinearGradient(0, 0, 0, 450);

this.gradient.addColorStop(0, "rgba(255, 0,0, 0.5)");
this.gradient.addColorStop(0.5, "rgba(255, 0, 0, 0.25)");
this.gradient.addColorStop(1, "rgba(255, 0, 0, 0)");

..but this.$refs.canvas is undefined in the parent component, which prevents me from getting the context, so I can't create a gradient.


回答1:


You can access this.$refs.canvas in your chart component. If you want to access it from your parent component there are several ways.

The fast unclean way is over this.$children https://vuejs.org/v2/api/#vm-children

A better way would be to setup the gradient stuff into a own method and pass in all data as props to your chart component.



来源:https://stackoverflow.com/questions/51022003/vue-chartjs-create-gradient-background-for-chart-from-child-component-canvas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!