【问题标题】:Error on Chart.js with Electron - Failed to create chart: can't acquire context from the given item使用 Electron 在 Chart.js 上出错 - 无法创建图表:无法从给定项目获取上下文
【发布时间】:2021-06-15 21:02:17
【问题描述】:

首先,我检查了以下帖子:

似乎没有人描述我遇到的相同问题,这就是我求助于创建新帖子的原因。

我已将代码隔离到最低限度 - 这实际上只是电子样板 + chart.js 样板。我已将其发布在以下 git repo https://github.com/HerveSV/chartjsElectronTest

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Hello World!</title>
  </head>
  <body>
    <h1>???? Hello World!</h1>
    <p>Welcome to your Electron application.</p>

    <div>
      <canvas id="chart" width="400" height="400"></canvas>
    </div>
   
    <script defer src="render.js"></script>

  </body>
</html>

preload.js(为了安全,访问节点 api 代替 render.js)

const { contextBridge } = require('electron')
const Chart = require("chart.js");


contextBridge.exposeInMainWorld(
    'electron',
    {
        createChart: (ctx, params) => {
          let chart = new Chart(ctx, params);
        }
    }
)

render.js


// neither work
let ctx = document.getElementById("chart").getContext("2d");
//let ctx = document.getElementById("chart");

console.log(ctx);
window.electron.createChart(ctx, {
    type: 'bar',
    data: {
        labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3],
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(75, 192, 192, 0.2)',
                'rgba(153, 102, 255, 0.2)',
                'rgba(255, 159, 64, 0.2)'
            ],
            borderColor: [
                'rgba(255, 99, 132, 1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)'
            ],
            borderWidth: 1
        }]
    },
    options: {
        scales: {
            y: {
                beginAtZero: true
            }
        }
    }
});

关于这个问题我无话可说,电子应用程序运行,其他一切正常,但图表应该在哪里有一个空白区域,并显示以下错误消息:无法创建图表:可以' t 从给定项目获取上下文。电子样板适用于其他所有内容,所以我不认为这是错误点。我直接从https://www.chartjs.org/docs/latest/ 复制了chart.js 样板代码,所以应该也可以。我确保获取 canvas 元素的 2d 上下文。我想知道这是否是 chart.js 节点模块的错误 - 但如果是这种情况,那么所有错误报告都在哪里?

如果有人能提供更多见解,将不胜感激。我只是很迷茫,在这里没有选择。

【问题讨论】:

    标签: javascript node.js charts electron chart.js


    【解决方案1】:

    有点晚了,但也许这会帮助其他有同样问题的人。 我遇到了同样的问题,我通过移动来解决问题

    ctx = document.getElementById("chart").getContext("2d");

    在 preload.js 中 似乎您无法将 domobject 从 renderer.js 传递给 preload.js

    【讨论】:

      猜你喜欢
      • 2017-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-10
      • 2019-10-21
      • 2020-09-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多