首页 > 解决方案 > 在 ChartJS 的 Chart-Canvas 区域中放置文本

问题描述

我创建了两个 x,y 数组,然后使用它们执行了两个图表。我想只用红色图表写一些文字。我想使用 (x,y) 坐标来确定文本区域。我尝试使用 Chartjs Global 插件,但它会导致在所有图表中写入文本。我要求只给一张图表发短信。我在脚本中的 Chartjs 单声道插件中无法成功。请帮我。

这是我的代码:

<!DOCTYPE html>
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div class="w3-row">
        <div class="w3-col s3"><p></p></div>
        <div class="w3-col s6" align="center"><canvas id="myChart" height="120"></canvas></div>
        <div class="w3-col s3"><p></p></div>
    </div>
    <div class="w3-row">
        <div class="w3-col s3"><p></p></div>
        <div class="w3-col s6" align="center"><canvas id="myTau" height="120"></canvas></div>
        <div class="w3-col s3"><p></p></div>
    </div>
</body>
</html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
<script type="text/javascript">
    var xCoord = new Array(1997, 2003, 2005, 2009, 2014, 2018, 2019);
    var yCoord = new Array(1, 3, 5, 3, 6, 10, 9);
    var c = [];
    for (var i = 0; i < xCoord.length; i++) {
        var obj = { x: xCoord[i], y: yCoord[i] };
        c.push(obj);
    }
        var ctx = document.getElementById('myChart').getContext('2d');
        var myChart = new Chart(ctx, {
            type: 'line',
            data: {
                datasets: [{
                    label: 'None',
                    data: c,
                    borderWidth: 1,
                    borderColor: "#3e95cd",
                    fill: false,
                    cubicInterpolationMode: 'monotone'
                }
                ]
            },
            options: {
                title: {
                    display: true,
                    text: 'My Chart'
                },
                tooltips: {
                    mode: 'nearest',
                    intersect: true
                },
                scales: {
                    xAxes: [{
                        type: 'linear',
                        position: 'bottom',
                        scaleLabel: {
                            display: true,
                            labelString: 'Year Assembly',
                            fontSize: 14
                                    }
                    }],
                    yAxes: [{
                        scaleLabel: {
                            display: true,
                            labelString: 'Aquifer Values',
                            fontSize: 15
                                    }
                    }]
                }
            }
        });
</script>

<script type="text/javascript">
    var xCoord = new Array(1997, 2003, 2005, 2009, 2014, 2018, 2019);
    var yCoord = new Array(41, 31, 11, 31, 88, 101, 91);
    var c = [];
    for (var i = 0; i < xCoord.length; i++) {
        var obj = { x: xCoord[i], y: yCoord[i] };
        c.push(obj);
    }
    var ctx = document.getElementById('myTau').getContext('2d');
    var myTau = new Chart(ctx, {
        type: 'line',
        data: {
            datasets: [{
                label: 'None',
                data: c,
                borderWidth: 1,
                borderColor: "#ef1414",
                fill: false,
                cubicInterpolationMode: 'monotone'
            }
            ]
        },
        options: {
            title: {
                display: true,
                text: 'My Chart 2'
            },
            tooltips: {
                mode: 'nearest',
                intersect: true
            },
            scales: {
                xAxes: [{
                    type: 'linear',
                    position: 'bottom',
                    scaleLabel: {
                        display: true,
                        labelString: 'Year Assembly',
                        fontSize: 14
                    }
                }],
                yAxes: [{
                    scaleLabel: {
                        display: true,
                        labelString: 'Aquifer Values Corresponding',
                        fontSize: 15
                    }
                }]
            }
        }
    });
</script>

更新:

这是另一个问题:

有没有办法通过chartjs坐标系来分配文本位置,而不是“宽度。高度。”?

例如,根据 xCoord & yCoord 数组,是否可以设置 ctx.fillText x,y 坐标的位置:

而不是 ctx.fillText("s(A)", width * .28, height * .70); 可以是这样的:ctx.fillText("s(A)", 2005, 3); (2015,9) 属于chartjs坐标系。

我的目标:s(A) 可以在 (2005,3) 点的 chartjs 区域看到 s(A) 可以在 (2015,9) 点的 chartjs 区域看到

我的坐标问题图片

这是最后一个问题代码:

<!DOCTYPE html>
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div class="w3-row">
        <div class="w3-col s3"><p></p></div>
        <div class="w3-col s6" align="center"><canvas id="myChart" height="120"></canvas></div>
        <div class="w3-col s3"><p></p></div>
    </div>
    <div class="w3-row">
        <div class="w3-col s3"><p></p></div>
        <div class="w3-col s6" align="center"><canvas id="myTau" height="120"></canvas></div>
        <div class="w3-col s3"><p></p></div>
    </div>
</body>
</html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
<script type="text/javascript">
    var plugin = {
        beforeDraw: function (chart) {
            var width = chart.chart.width,
                height = chart.chart.height,
                ctx = chart.chart.ctx;
            ctx.restore();
            ctx.font = "1em sans-serif";
            ctx.textAlign = "center";
            ctx.textBaseline = "middle";
            ctx.fillText("s(A)", width * .28, height * .70);
            ctx.fillText("s(B)", width * .75, height * .55);
            //These section were set according to canvas width and height
            //I want to set coordinates chartjs coordinates like in data {x:1993,y:70}
             // Doesnt Work Like This: ctx.fillText("s(A)", 2005, 2);
             //Doesnt Work Like This: ctx.fillText("s(B)", 2015, 9);
            ctx.save();
        }
    };
    Chart.plugins.register(plugin);

    var xCoord = new Array(1997, 2003, 2005, 2009, 2014, 2018, 2019);
    var yCoord = new Array(1, 3, 5, 3, 6, 10, 9);
    var c = [];
    for (var i = 0; i < xCoord.length; i++) {
        var obj = { x: xCoord[i], y: yCoord[i] };
        c.push(obj);
    }
        var ctx = document.getElementById('myChart').getContext('2d');
        var myChart = new Chart(ctx, {
            type: 'line',
            data: {
                datasets: [{
                    label: 'None',
                    data: c,
                    borderWidth: 1,
                    borderColor: "#3e95cd",
                    fill: false,
                    cubicInterpolationMode: 'monotone'
                }
                ]
            },
            options: {
                plugins: [plugin],
                title: {
                    display: true,
                    text: 'My Chart'
                },
                tooltips: {
                    mode: 'nearest',
                    intersect: true
                },
                scales: {
                    xAxes: [{
                        type: 'linear',
                        position: 'bottom',
                        scaleLabel: {
                            display: true,
                            labelString: 'Year Assembly',
                            fontSize: 14
                                    }
                    }],
                    yAxes: [{
                        scaleLabel: {
                            display: true,
                            labelString: 'Aquifer Values',
                            fontSize: 15
                                    }
                    }]
                }
            }
        });
</script>

标签: asp.net-corecanvashtml5-canvaschart.js

解决方案


一个工作示例:

var plugin = {
  id: 'plugin',
  beforeDraw: function(chart) {

    var width = chart.chart.width,
      height = chart.chart.height,
      ctx = chart.chart.ctx,
      xScale = chart.scales['x-axis-0'],
      yScale = chart.scales['y-axis-0'];

    ctx.restore();
    ctx.font = "1em sans-serif";
    ctx.textAlign = "center";
    ctx.textBaseline = "middle";
    // ctx.fillText("s(A)", width * .28, height * .70);
    ctx.fillText(
      "s(A)",
      xScale.getPixelForValue('2005'),
      yScale.getPixelForValue(3)
    );
    ctx.fillText(
      "s(B)",
      xScale.getPixelForValue('2015'),
      yScale.getPixelForValue(9)
    );
    ctx.save();
  }
};

var xCoord = new Array(1997, 2003, 2005, 2009, 2014, 2018, 2019);
var yCoord = new Array(1, 3, 5, 3, 6, 10, 9);
var c = [];
for (var i = 0; i < xCoord.length; i++) {
  var obj = {
    x: xCoord[i],
    y: yCoord[i]
  };
  c.push(obj);
}
var ctx = document.getElementById('myTau').getContext('2d');
var myTau = new Chart(ctx, {
  type: 'line',
  data: {
    datasets: [{
      label: 'None',
      data: c,
      borderWidth: 1,
      borderColor: "#ef1414",
      fill: false,
      cubicInterpolationMode: 'monotone'
    }]
  },
  plugins: [plugin],
  options: {
    title: {
      display: true,
      text: 'My Chart 2'
    },
    tooltips: {
      mode: 'nearest',
      intersect: true
    },
    scales: {
      xAxes: [{
        type: 'linear',
        position: 'bottom',
        scaleLabel: {
          display: true,
          labelString: 'Year Assembly',
          fontSize: 14
        }
      }],
      yAxes: [{
        scaleLabel: {
          display: true,
          labelString: 'Aquifer Values Corresponding',
          fontSize: 15
        }
      }]
    }
  }
});
var ctx = document.getElementById('myTax').getContext('2d');
var myTau = new Chart(ctx, {
  type: 'line',
  data: {
    datasets: [{
      label: 'None',
      data: c,
      borderWidth: 1,
      borderColor: "#ef1414",
      fill: false,
      cubicInterpolationMode: 'monotone'
    }]
  },
  options: {
    title: {
      display: true,
      text: 'My Chart 2'
    },
    tooltips: {
      mode: 'nearest',
      intersect: true
    },
    scales: {
      xAxes: [{
        type: 'linear',
        position: 'bottom',
        scaleLabel: {
          display: true,
          labelString: 'Year Assembly',
          fontSize: 14
        }
      }],
      yAxes: [{
        scaleLabel: {
          display: true,
          labelString: 'Aquifer Values Corresponding',
          fontSize: 15
        }
      }]
    }
  }
});
<canvas id="myTau" height="120"></canvas>
<canvas id="myTax" height="120"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

创建并注册一个plugin绘制文本的新对象,然后仅在第二个图表上调用它,您也可以传递数据(例如标签数组和每个标签的位置)。


更新:(注册插件)

如果您在全局注册插件,则必须在此处禁用每个图表中的插件,您不希望它运行。

options: {
    plugins: {
        plugin: false
    }
}

- 或者 -

如果您没有全局注册插件,请在需要添加标签的每个图表中添加以下内容:

{
    plugins: [plugin]
}

注意:在第二段代码plugin中没有嵌套在options. 看到这里


更新:(使用数据集显示文本x,y

为了使用一个x,y值,您需要使用其 id 来识别您的值,默认值为x-axis-0y-axis-0,如果您添加更多轴,则该值会增加。或使用自定义轴 ID。

之后,在chart实例中有一个表示轴的比例对象,使用chart.scales['x-axis-0']您可以访问一个调用的函数,该函数getPixelForValue会将给定值从该轴转换为其像素位置。


推荐阅读