【问题标题】:Place Text in Chart-Canvas Area in ChartJS在 ChartJS 的 Chart-Canvas 区域中放置文本
【发布时间】:2019-09-20 21:10:55
【问题描述】:

我创建了两个 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区域看到

My Coordinate Problem Picture

这是最后一个问题代码:

<!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-core canvas html5-canvas chart.js


    【解决方案1】:

    一个工作示例:

    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 的第二个sn-p 中没有嵌套在options 下。见here。


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

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

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

    【讨论】:

    • 当我尝试时,这段代码做得很好,但在这个问题中,所有图表都写好了。
    • @drakislow,我已经更新了我的答案,请再次查看示例,让我知道结果。
    • 结果很完美。非常感谢先生。
    • 有没有办法通过chartjs坐标系来管理文本位置,而不是宽度。,高度。? @francisco-soares
    • @drakislow 我不这么认为,但请解释一下你到底想要达到什么,也许可以用其他方式计算位置。
    【解决方案2】:

    <!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);
                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>
    
    <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>

    这里有问题。文字是写所有图表。我的目标是只红色一张图表(我的图表 2)。

    【讨论】:

      猜你喜欢
      • 2019-10-08
      • 2021-09-24
      • 2015-09-07
      • 1970-01-01
      • 2013-05-18
      • 1970-01-01
      • 2013-05-12
      • 2015-12-21
      • 1970-01-01
      相关资源
      最近更新 更多