(Vue, ChartJS) Create gradient background for chart from child component canvas context((Vue, ChartJS) 从子组件画布上下文为图表创建渐变背景)
问题描述
我想给我的图表一个渐变背景颜色,但我无法访问画布上下文,因为我的图表在我编写的包装器组件中呈现.
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) 从子组件画布上下文为图表创建渐变背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:(Vue, ChartJS) 从子组件画布上下文为图表创建渐变背景


基础教程推荐
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 动态更新多个选择框 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01