-1

I have followed this question to achieve an arbitrary line:
Chart.js — drawing an arbitrary vertical line

Fiddle

I use this line of code to change to dashed:

this.chart.ctx.setLineDash([3]);

but this changes the line on the chart too, I only want to change the arbitrary line stroke. How can I adapt this?

Thanks.

Community
  • 1
  • 1
user1937021
  • 10,151
  • 22
  • 81
  • 143

1 Answers1

2

Just wrap the block where you set the ctx properties and draw with the following lines to save and restore the context,

this.chart.ctx.save();
...
this.chart.ctx.restore();

Fiddle - http://jsfiddle.net/ps3186ex/

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.save();
    this.chart.ctx.setLineDash([3]);
    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();
    this.chart.ctx.restore();

    // 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
});
<script src='https://rawgit.com/nnnick/Chart.js/v1.0.2/Chart.min.js'></script>
<canvas id="LineWithLine" width="600" height="400"></canvas>
markE
  • 102,905
  • 11
  • 164
  • 176
potatopeelings
  • 40,709
  • 7
  • 95
  • 119
  • 1
    Good answer, but please use [StackSnippets](https://blog.stackoverflow.com/2014/09/introducing-runnable-javascript-css-and-html-code-snippets/) so the answer's code shows in the answer and to avoid link rot. – markE May 01 '16 at 05:02