如何使用chart.js 3.x绘制水平线?无法让它工作

问题描述 投票:0回答:3

目标

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

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

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

预期结果

应该是这样的。

实际结果

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

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

到目前为止我所尝试过的

Jsfiddle - 未尝试工作

<!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
3个回答
3
投票

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 - 工作


2
投票

插件是向ChartJS添加自定义功能的一种非常常见的方法。它允许我们使用插件对象提供的钩子来操作事件。

在这个简单的示例中,我们将创建一个 ID 为

horizontalLines
的插件。然后,我们将调用
afterDraw
钩子来渲染水平线,该钩子在图表渲染后调用。

const $canvas = document.getElementById('chart')

const plugin = {
    id: 'horizontalLines',
    defaults: {
        lines: []
    },
    afterDraw: (chart, _, options) => {
        const { ctx } = chart
        const { left, right } = chart.chartArea

        const lines = options.lines
        if (!lines) return
        for (const line of lines) {
            const scale = chart.scales.y
            
            const width = line.width || 1
            const color = line.color || 'rgba(169,169,169, .6)'
            const value = line.value ? scale.getPixelForValue(line.value) : 0
            const label = line.label || null

            if (value) {
                ctx.beginPath()
                ctx.lineWidth = width
                ctx.moveTo(left, value)
                ctx.lineTo(right, value)
                ctx.strokeStyle = color
                ctx.stroke()
            }

            if (label) {
                ctx.fillStyle = color
                ctx.fillText(label, right - label.length*5, value + width)
            }
        }

        return
    }
}



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

Chart.register(plugin)

const chart = new Chart($canvas, {
    type: 'line',
    data: data,
    options: {
        maintainAspectRatio: false,
        plugins: {
            'horizontalLines': {
                lines: [{
                    value: 75.8,
                    color: 'red',
                    label: 'upper',
                },
                {
                    value: 62.3,
                    color: 'lime',
                    label: 'avg',
                },
                {
                    value: 48.8,
                    color: 'blue',
                    label: 'lower',
                }]
            },
        },
    }
})
.container {
  position: relative;
  width: 90vw;
}
<div class="container">
  <canvas id="chart"></canvas>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js"></script>

我使用最新版本的ChartJs

添加了一个版本

const $canvas = document.getElementById('chart')

const plugin = {
    id: 'horizontalLines',
    defaults: {
        lines: []
    },
    afterDraw: (chart, _, options) => {
        const { ctx } = chart
        const { left, right } = chart.chartArea

        const lines = options.lines
        if (!lines) return
        for (const line of lines) {
            const scale = chart.scales.y
            
            const width = line.width || 1
            const color = line.color || 'rgba(169,169,169, .6)'
            const value = line.value ? scale.getPixelForValue(line.value) : 0
            const label = line.label || null

            if (value) {
                ctx.beginPath()
                ctx.lineWidth = width
                ctx.moveTo(left, value)
                ctx.lineTo(right, value)
                ctx.strokeStyle = color
                ctx.stroke()
            }

            if (label) {
                ctx.fillStyle = color
                ctx.fillText(label, right - label.length*5, value + width)
            }
        }

        return
    }
}


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

Chart.register(plugin)

const chart = new Chart($canvas, {
    type: 'line',
    data: data,
    options: {
        maintainAspectRatio: false,
        plugins: {
            'horizontalLines': {
                lines: [{
                    value: 75.8,
                    color: 'red',
                    label: 'upper',
                },
                {
                    value: 62.3,
                    color: 'lime',
                    label: 'avg',
                },
                {
                    value: 48.8,
                    color: 'blue',
                    label: 'lower',
                }]
            },
        },
    }
})
<div class="container">
  <canvas id="chart"></canvas>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.1/chart.umd.js" integrity="sha512-ZwR1/gSZM3ai6vCdI+LVF1zSq/5HznD3ZSTk7kajkaj4D292NLuduDCO1c/NT8Id+jE58KYLKT7hXnbtryGmMg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>


0
投票

我在使用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);
© www.soinside.com 2019 - 2024. All rights reserved.