问题
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