【问题标题】:How to draw horizontal Lines using chart.js 3.x ? Cannot get it working如何使用 chart.js 3.x 绘制水平线?无法让它工作
【发布时间】:2021-05-31 20:15:31
【问题描述】:

目标

我想在我的 html 页面中通过 CDN 集成使用 Chart.js 3.x 创建一个由三个水平线组成的图表,覆盖我的实际数据集线。

所以,我没有自己的 Chart.js 安装,但正在使用 CDN。到目前为止,我以这种方式使用最新的 Chart.js 3.x Beta 版本没有真正的问题。

重要提示:由于我需要它的一些额外 Beta 功能,我无法恢复到稳定的 Chart.js 2.x。

预期结果

That's how it should like alike.

实际结果

我使用 Chart.js 版本 3.0.0-beta.6 根据我的数据集创建实际折线图没有问题。 如果您在 JavaScript Fiddle 部分的第 64 行添加注释,您将看到基本图表正在运行。

但是,不幸的是,我无法绘制水平线!

到目前为止我已经尝试过什么

Jsfiddle - not working attempt

<!DOCTYPE html>
<html lang="en">
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.0.0-beta.6/chart.js"></script>

  <style>
    .container{
      position: relative;
      width: 50vw;
    }
  </style>
</head>
<body>
  <canvas id="myChart" class="container"></canvas>

<script>
  var canvas = document.getElementById("myChart");
  var ctx = canvas.getContext("2d");

  var horizonalLinePlugin = {
    id: 'horizontalLine',
    afterDraw: function(chartInstance) {
    var yScale = chartInstance.scales["y-axis-0"];
    var canvas = chartInstance.chart;
    var ctx = canvas.ctx;
    var index;
    var line;
    var style;

    if (chartInstance.options.horizontalLine) {
      for (index = 0; index < chartInstance.options.horizontalLine.length; index++) {
        line = chartInstance.options.horizontalLine[index];

        if (!line.style) {
          style = "rgba(169,169,169, .6)";
        } else {
          style = line.style;
        }

        if (line.y) {
          yValue = yScale.getPixelForValue(line.y);
        } else {
          yValue = 0;
        }

        ctx.lineWidth = 3;

        if (yValue) {
          ctx.beginPath();
          ctx.moveTo(0, yValue);
          ctx.lineTo(canvas.width, yValue);
          ctx.strokeStyle = style;
          ctx.stroke();
        }

        if (line.text) {
          ctx.fillStyle = style;
          ctx.fillText(line.text, 0, yValue + ctx.lineWidth);
        }
      }
      return;
    }
  }
};


var data = {
  labels: ["January", "February", "March", "April", "May", "June", "July"],
  datasets: [{
    label: "MyDataset01",
    fill: false,
    lineTension: 0.1,
    backgroundColor: "rgba(75,192,192,0.4)",
    borderColor: "rgba(75,192,192,1)",
    data: [65, 59, 80, 81, 56, 55, 40],
  }]
};

//When uncommenting below line, graph is created without horizontal lines
Chart.register(horizonalLinePlugin);
var myChart = new Chart(ctx, {
  type: 'line',
  data: data,
  options: {
    "horizontalLine": [{
      "y": 75.8,
      "style": "#ff0000",
      "text": "upper-limit"
    }, {
      "y": 62.3,
      "style": "#00ff00",
      "text": "avg"
    }, {
      "y": 48.8,
      "style": "#0000ff",
      "text": "lower-limit"
    }]
  }
});
</script>

我阅读了 Chart.js 的文档和 chartjs-annotation-plugin 的工作示例 - 但不幸的是,所有这些都仅基于 Chart.js 版本 2.x。

我没有设法让它在短期内尝试 CDN https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.0.0-beta.6/chart.jshttps://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-annotation/0.5.7/chartjs-plugin-annotation.js 一起。没有找到任何工作,例如小提琴示例。

现在我尝试使用内联 Chart.js 插件但没有成功,例如错误信息

Fiddle JavaScript 部分的第 8 行:“#55:15 TypeError: canvas is undefined”

【问题讨论】:

    标签: javascript jquery charts chart.js chart.js3


    【解决方案1】:

    chartInstance.chart 未定义。不确定是否存在迁移到 chart.js 3.0 版的问题...

    尝试以下方法:

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <!-- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> -->
      <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.0.0-beta.6/chart.js"></script>
    
      <style>
        .container{
          position: relative;
          width: 50vw;
        }
      </style>
    </head>
    <body>
      <canvas id="myChart" class="container"></canvas>
    
    <script>
      var canvas = document.getElementById("myChart");
      var ctx = canvas.getContext("2d");
    
      var horizonalLinePlugin = {
        id: 'horizontalLine',
        afterDraw: function(chartInstance) {
        var yScale = chartInstance.scales["y"];
    
        // chartInstance.chart is undefined
        //var canvas = chartInstance.chart;
       // console.log(canvas);
       // var ctx = canvas.ctx;
        var index;
        var line;
        var style;
    
        if (chartInstance.options.horizontalLine) {
          for (index = 0; index < chartInstance.options.horizontalLine.length; index++) {
            line = chartInstance.options.horizontalLine[index];
    
            if (!line.style) {
              style = "rgba(169,169,169, .6)";
            } else {
              style = line.style;
            }
    
            if (line.y) {
              yValue = yScale.getPixelForValue(line.y);
            } else {
              yValue = 0;
            }
    
            ctx.lineWidth = 3;
    
            if (yValue) {
              ctx.beginPath();
              ctx.moveTo(0, yValue);
              ctx.lineTo(canvas.width, yValue);
              ctx.strokeStyle = style;
              ctx.stroke();
            }
    
            if (line.text) {
              ctx.fillStyle = style;
              ctx.fillText(line.text, 0, yValue + ctx.lineWidth);
            }
          }
          return;
        }
      }
    };
    
    
    var data = {
      labels: ["January", "February", "March", "April", "May", "June", "July"],
      datasets: [{
        label: "MyDataset01",
        fill: false,
        lineTension: 0.1,
        backgroundColor: "rgba(75,192,192,0.4)",
        borderColor: "rgba(75,192,192,1)",
        data: [65, 59, 80, 81, 56, 55, 40],
      },
    ]
    };
    //When uncommenting below line, graph is created without horizontal lines
    Chart.register(horizonalLinePlugin);
    var myChart = new Chart(ctx, {
      type: 'line',
      data: data,
      options: {
        "horizontalLine": [{
          "y": 75.8,
          "style": "#ff0000",
          "text": "upper-limit"
        }, {
          "y": 62.3,
          "style": "#00ff00",
          "text": "avg"
        }, {
          "y": 48.8,
          "style": "#0000ff",
          "text": "lower-limit"
        }],
    
        
       
      }
    });
    </script>
    

    这是上面Jsfiddle - working中的代码!

    【讨论】:

    • 太好了 - 非常感谢!希望不要显得忘恩负义甚至永不满足:是否有机会 a) 为每条水平线单独设置 lineWidth = borderWidth 甚至更好 b) 使用 chartjs-plugin-annotation.js 和 chartjs 版本 3 提供一个工作小提琴。 x 提供了更多的配置可能性:-) ?
    【解决方案2】:

    我在使用 chartjs 3.0 时遇到了同样的问题。我使用以下代码来显示水平线

    var horizonalLinePlugin = {
    id : 'horizontalLine',
    afterDraw: function (chartInstance) {
        // var yScale = chartInstance.scales["y-axis-0"];
        var yScale = chartInstance.scales['y'];
        // var canvas = chartInstance.chart;
        var canvas = chartInstance.canvas;
        var ctx = chartInstance.ctx;
        var index;
        var line;
        var style;
        var yValue;
    
        if (chartInstance.config._config.options.horizontalLine) {
            for (index = 0; index < chartInstance.config._config.options.horizontalLine.length; index++) {
                line = chartInstance.config._config.options.horizontalLine[index];
    
                if (!line.style) {
                    style = "rgba(169,169,169, .6)";
                } else {
                    style = line.style;
                }
    
                if (line.y) {
                    yValue = yScale.getPixelForValue(line.y);
                } else {
                    yValue = 0;
                }
    
                ctx.lineWidth = 3;
    
                if (yValue) {
                    ctx.beginPath();
                    ctx.moveTo(20, yValue);
                    // ctx.moveTo(0, yValue);
                    ctx.lineTo(canvas.width, yValue);
                    ctx.strokeStyle = style;
                    ctx.stroke();
                }
    
                if (line.text) {
                    ctx.fillStyle = style;
                    ctx.fillText(line.text, 0, yValue + ctx.lineWidth);
                }
            }
            return;
        };
    }
    };
    Chart.register(horizonalLinePlugin);
    

    【讨论】:

      猜你喜欢
      • 2015-09-14
      • 1970-01-01
      • 1970-01-01
      • 2022-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-27
      相关资源
      最近更新 更多