我正在尝试使用Charts.js来动态显示它们在示例中显示的默认线图,并将其放在我在用户单击时弹出的div中.我的代码是这样的:
this.chartCanvas = document.createElement('canvas');
this.div.appendChild(this.chartCanvas);
this.chartCanvas.style.height = '480px';
this.chartCanvas.style.width = '900px';
this.chartCanvas.width = 900;
this.chartCanvas.height = 480;
this.ctx = this.chartCanvas.getContext('2d');
this.chart = new Chart(this.ctx).Line(data);
Run Code Online (Sandbox Code Playgroud)
当我调用"新图表"时,我的画布高度和宽度设置为0,正如我在检查器中看到的那样.当我注释掉这个调用时,我的画布具有适当的宽度/高度并显示为人们所期望的.如果我在检查器中手动更改画布高度/宽度,我的图表仍然不会显示.
我的"数据"对象就是我直接从他们的折线图中剪切和粘贴的对象:http://www.chartjs.org/docs/#line-chart-example-usage
任何人都可以提供一些关于我可能出错的地方的见解,我对图书馆来说是全新的.
这确实是我第一次使用Chart.js,并将其导入到Angular组件中。我现在尝试仅创建一个简单的条形图。我的控制台出现以下错误:
core.controller.js:118 Failed to create chart: can't acquire context from the given item
不知道我在做什么错!
这是我的组件的TS文件:
import { Component, OnInit } from '@angular/core';
import { Chart } from 'chart.js';
import { data } from './data';
@Component({
selector: 'app-propel-factor',
templateUrl: './propel-factor.component.html'
})
export class PropelFactorComponent implements OnInit {
chart = [];
labels: any = [];
data: any = [];
constructor() { }
ngOnInit() {
data.forEach(item => {
this.labels.push(item.name);
this.data.push(item.value);
});
this.chart = new Chart('canvas', {
type: 'bar',
labels: this.labels,
data: {
labels: …Run Code Online (Sandbox Code Playgroud) 我有这个组件,它使用react-chartjs-2来渲染Doughnut图表:
const CompliancyChart = ({data}): JSX.Element => {
...
return (
<ChartStyled>
{chartPlugins && chartData && (
<Doughnut
aria-label="Compliancy Chart"
data={chartData}
options={chartOptions}
plugins={chartPlugins}
/>
)}
</ChartStyled>
);
};
Run Code Online (Sandbox Code Playgroud)
我有一个该组件的测试文件,其中包含以下断言:
describe('Chart component', () => {
afterEach(() => {
cleanup();
});
test('should render without errors', async () => {
render(<CompliancyChart data={mockCompliancyChartData} />, {});
const compliancyChart = await screen.findByRole('img', {
name: 'Compliancy Chart',
});
expect(compliancyChart).toBeDefined();
});
});
Run Code Online (Sandbox Code Playgroud)
该测试工作正常,但我不断在测试控制台中收到此错误:
Failed to create chart: can't acquire context from the given item …Run Code Online (Sandbox Code Playgroud)