简体   繁体   English

在 ChartJS 散点图中显示图像而不是一个点

[英]Show image instead a point in a ChartJS scatter plot

I am trying to replace points of a scatter plot with a PNG image.我正在尝试用 PNG 图像替换散点图的点。 Based on the documentation, the pointStyle accepts either a string or an image.根据文档, pointStyle接受字符串或图像。 However instead of the image on the first point, it just shows a regular scatter plot point.然而,它只是显示了一个规则的散点图点,而不是第一个点上的图像。 Any ideas?有任何想法吗?

 var ctx = document.getElementById("myChart").getContext('2d'); var img = new Image(); var img1 = img.src = 'assets/img/small/STORM.png'; var imageData = { datasets: [{ pointStyle: [img1, 'rect', 'triangle', 'circle'], data: [{ x: 1.447377, y: -0.014573 }, { x: 2.365398, y: -1.062847 }, { x: -2.507778, y: 0.389309 }, { x: -0.432636, y: 0.124841 }] }] } var myChart = new Chart(ctx, { type: 'scatter', data: imageData, options: {} });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0/dist/Chart.min.js"></script> <canvas id="myChart" width="400" height="400"></canvas>

You can see a working example in jsfiddle here您可以在此处的 jsfiddle 中看到一个工作示例

According to Chart.js documentation , pointStyle is either a string or an Image but not an array.根据Chart.js 文档pointStylestringImage但不是数组。

If you want to have individual styles for your points, you can use the Plugin Core API .如果您想为您的点设置单独的样式,您可以使用插件核心 API It offers several hooks that may be used for executing custom code.它提供了几个可用于执行自定义代码的钩子。 You could use the afterDraw hook to assign a different pointStyle to each point.您可以使用afterDraw钩子为每个点分配不同的pointStyle

plugins: {
  afterUpdate: function(chart) {
    const meta = chart.getDatasetMeta(0);
    meta.data[0]._model.pointStyle = img;
    meta.data[1]._model.pointStyle = 'rect';
    meta.data[2]._model.pointStyle = 'triangle';
    meta.data[3]._model.pointStyle = 'circle';
  }
},

I your amended code below, I used a slightly different but more compact approach and defined the pointStyles array outside of the chart configuration.我在下面修改了代码,我使用了一种稍微不同但更紧凑的方法,并在图表配置之外定义了pointStyles数组。

 const img = new Image(); img.src = 'https://i.stack.imgur.com/gXQrT.png'; const pointStyles = [img, 'rect', 'triangle', 'circle']; new Chart(document.getElementById('myChart'), { type: 'scatter', plugins: { afterUpdate: chart => { chart.getDatasetMeta(0).data.forEach((d, i) => d._model.pointStyle = pointStyles[i]); } }, data: { datasets: [{ data: [ {x: 1.447377, y: -0.014573}, {x: 2.365398, y: -1.062847}, {x: -2.507778, y: 0.389309}, {x: -0.432636, y: 0.124841} ], backgroundColor: ['white', 'green', 'red', 'orange'], pointRadius: 10 }] }, options: { legend: { display: false } } });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script> <canvas id="myChart" height="90"></canvas>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM