首页 > 解决方案 > 我可以使用 chartJS 绘制带有矩形的股票地图吗?

问题描述

我正在寻找一种解决方案来表示带有矩形的股票地图,如下图所示。是否可以使用 ChartJS 或者我应该使用另一个库?

在此处输入图像描述

标签: chart.js

解决方案


您可以使用来自.chartjs-plugin-annotation

请看下面的可运行代码,看看它是如何工作的。

const rectangles = [
  { x: 2, y: 2, width: 8, height: 5 },
  { x: 2, y: 9, width: 8, height: 5 },
  { x: 2, y: 16, width: 8, height: 5 },
  { x: 2, y: 23, width: 8, height: 5 },
  { x: 12, y: 2, width: 5, height: 5 },
  { x: 12, y: 9, width: 12, height: 7 },
  { x: 25, y: 11, width: 8, height: 4 },  
  { x: 18, y: 2, width: 8, height: 5 },
  { x: 16, y: 26, width: 16, height: 8 }
]

rectangles.forEach(r => {
  r.type = 'box';
  r.backgroundColor = 'rgba(0,180,0,0.02)';
  r.borderColor = 'rgb(0,180,0)';
  r.borderWidth = 1;
  r.borderRadius = 4;
  r.xMin = r.x;
  r.yMin = r.y;
  r.xMax = r.x + r.width;
  r.yMax = r.y + r.height;
});

new Chart('myChart', {
  type: 'scatter',
  options: {
    plugins: {
      annotation: {
        annotations: rectangles
      }
    },
    scales: {
      x: {
        min: 0,
        max: 35
      },
      y: {
        min: 0,
        max: 35
      }
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-annotation/1.0.2/chartjs-plugin-annotation.min.js"></script>
<canvas id="myChart"></canvas>


推荐阅读