在 Next.js 应用程序的 Chart.js 图表中为 pointStyles 使用 react-icons

问题描述

问题:
我正在尝试在 Chart.js 中使用 react-icons MdNavigation 图标作为 pointStyle。该应用程序是在 Next.js 中构建的。如果无法为 chart.js pointStyle 使用 react-icons,我愿意使用导入的 SVG、jpg 或 png 图标,但即使如此,我仍然遇到可能由我在中的文件加载器设置引起的问题next.config.js.

预期结果:
我希望 MdNavigation 图标 (https://react-icons.github.io/react-icons/icons?name=md) 显示为 pointStyles。

实际结果:
我已经尝试了一些不同的设置来让它工作,但到目前为止,他们都没有给我正确的图标。
我在一些不同的配置中遇到以下错误

未捕获的 DOMException:无法在“CanvasRenderingContext2D”上执行“drawImage”:提供的 HTMLImageElement 处于“损坏”状态。

配置 #1 以返回上述错误

const arrow = new Image()
arrow.src = <MdNavigation/>
...
        pointStyle: arrow,

我在进行以下设置时遇到同样的错误

const arrow = new Image()
arrow.src = MdNavigation
...
const mixedChartConfig = {
    type: 'bar',data: {
        datasets: [
            {
                label: 'Wind Gust (m/s)',data: state.data[0].data.hours
                    .slice(state.firstData,state.lastData)
                    .map(item => {
                        return item.gust.sg
                    }),// gust data here
                type: 'line',pointStyle: arrow,radius: 15,rotation: windDirectionArray
            }
        ],

为了为 MdNavigation 图标创建包装器,我还尝试了以下设置:

const arrow = () => {
    <div>
        <MdNavigation/>
    </div>
}

理想情况下,我想使用该图标作为 pointStyle。如果这是不可能的,我愿意使用另一个 jpg 或 png 图像,但我仍然遇到问题。以下代码是我尝试使用不同图像时的设置(可能是由我的文件加载器设置引起的。我对这些配置文件还不是很好)。此设置还给我以下错误

未捕获的 DOMException:无法在“CanvasRenderingContext2D”上执行“drawImage”:提供的 HTMLImageElement 处于“损坏”状态。

const arrow = new Image()
arrow.src = '../../public/arrow.jpg'
...
const mixedChartConfig = {
    type: 'bar',rotation: windDirectionArray
            }
       ],

加载程序配置 (next.config.js):

module.exports = {
  webpack: (config,options) => {
    config.module.rules.push({
      test: [/\.svg$/,/\.gif$/,/\.jpe?g$/,/\.png$/],use: [
        options.defaultLoaders.file-loader,{
          loader: 'file-loader',options: pluginoptions.options,},],})

    return config
  },

还尝试在 webpack.config.js 中进行设置:

module.exports = {
  module: {
    rules: [
      {
        test: /\.(png|jpe?g|gif)$/i,loader: 'file-loader',options: {
          publicPath: (url,resourcePath,context) => {
            // `resourcePath` is original absolute path to asset
            // `context` is directory where stored asset (`rootContext`) or `context` option

            // To get relative path you can use
            // const relativePath = path.relative(context,resourcePath);

            if (/my-custom-image\.png/.test(resourcePath)) {
              return `other_public_path/${url}`
            }

            if (/images/.test(context)) {
              return `image_output_path/${url}`
            }

            return `public_path/${url}`
          }
        }
      }
    ]
  }
}

解决方法

尝试将图像放在您的 public 文件夹中,并在没有 ... 的情况下引用它:

arrow.src = '/arrow.jpg'

这是我的领导: https://stackoverflow.com/a/65793150/194515