Chart.js — 绘制任意垂直线

Chart.js — drawing an arbitrary vertical line(Chart.js — 绘制任意垂直线)
本文介绍了Chart.js — 绘制任意垂直线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 Chart.js 在 x 轴上的特定点绘制垂直线?

How can I draw an vertical line at a particular point on the x-axis using Chart.js?

特别是,我想在 LineChart 上画一条线来表示当天.这是图表的模型:

In particular, I want to draw a line to indicate the current day on a LineChart. Here's a mockup of the chart: http://i.stack.imgur.com/VQDWR.png

推荐答案

更新 - 此答案适用于 Chart.js 1.x,如果您正在寻找 2.x 答案,请查看评论和其他答案.

解决方案

您扩展折线图并在绘图函数中包含用于绘制线条的逻辑.

Update - this answer is for Chart.js 1.x, if you are looking for a 2.x answer check the comments and other answers.

预览

HTML

HTML
<canvas id="LineWithLine" width="600" height="400"></canvas></div>

<div> <canvas id="LineWithLine" width="600" height="400"></canvas> </div>

脚本

var data = {
    labels: ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"],
    datasets: [{
        data: [12, 3, 2, 1, 8, 8, 2, 2, 3, 5, 7, 1]
    }]
};

var ctx = document.getElementById("LineWithLine").getContext("2d");

Chart.types.Line.extend({
    name: "LineWithLine",
    draw: function () {
        Chart.types.Line.prototype.draw.apply(this, arguments);

        var point = this.datasets[0].points[this.options.lineAtIndex]
        var scale = this.scale

        // draw line
        this.chart.ctx.beginPath();
        this.chart.ctx.moveTo(point.x, scale.startPoint + 24);
        this.chart.ctx.strokeStyle = '#ff0000';
        this.chart.ctx.lineTo(point.x, scale.endPoint);
        this.chart.ctx.stroke();

        // write TODAY
        this.chart.ctx.textAlign = 'center';
        this.chart.ctx.fillText("TODAY", point.x, scale.startPoint + 12);
    }
});

new Chart(ctx).LineWithLine(data, {
    datasetFill : false,
    lineAtIndex: 2
});

选项属性 lineAtIndex 控制在哪个点画线.

The option property lineAtIndex controls which point to draw the line at.

小提琴 - http://jsfiddle.net/dbyze2ga/14/

这篇关于Chart.js — 绘制任意垂直线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Update another component when Formik form changes(当Formik表单更改时更新另一个组件)
Formik validation isSubmitting / isValidating not getting set to true(Formik验证正在提交/isValiating未设置为True)
React Validation Max Range Using Formik(使用Formik的Reaction验证最大范围)
Validation using Yup to check string or number length(使用YUP检查字符串或数字长度的验证)
Updating initialValues prop on Formik Form does not update input value(更新Formik表单上的初始值属性不会更新输入值)
password validation with yup and formik(使用YUP和Formick进行密码验证)