我想给我的图表一个渐变背景颜色,但我无法访问画布上下文,因为我的图表在我编写的包装器组件中呈现.
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.
我想要实现的目标:
我的实际包装器看起来像这样:
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
在父组件中未定义,这使我无法获取上下文,因此无法创建渐变.
..but this.$refs.canvas
is undefined in the parent component, which prevents me from getting the context, so I can't create a gradient.
您可以在图表组件中访问 this.$refs.canvas
.如果你想从你的父组件访问它,有几种方法.
You can access this.$refs.canvas
in your chart component.
If you want to access it from your parent component there are several ways.
快速不干净的方法就结束了.$childrenhttps://vuejs.org/v2/api/#vm-children
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.
这篇关于(Vue, ChartJS) 从子组件画布上下文为图表创建渐变背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!