Home Forums Chart Support Drawing defined horizontal lines Reply To: Drawing defined horizontal lines

#37273

@tbates,

You can achieve similar result in React by adding methods calculateValuesInPixel and drawHorizontalLines in component and call respective methods in the ComponentDidMount lifecycle method as shown in the below code snippet.

class App extends Component {
  constructor(props) {
    super(props);
    this.points = [
      { x1: 35, x2: 75, y: 75}, //line 1
      { x1: 35, x2: 75, y: 35}  //line 2
    ];	
    this.valuesInPixel = [
      { x1: null, x2: null, y: null}, //line 1
      { x1: null, x2: null, y: null}  //line 2
    ];
  }

  calculateValuesInPixel = () => {
    for(var i = 0; i < this.points.length; i++) {
      this.valuesInPixel[i].x1 = this.chart.axisX[0].convertValueToPixel(this.points[i].x1);
      this.valuesInPixel[i].x2 = this.chart.axisX[0].convertValueToPixel(this.points[i].x2);
      this.valuesInPixel[i].y = this.chart.axisY[0].convertValueToPixel(this.points[i].y);
    }
  } 
   
  drawHorizontalLines = () => {
    for(var i = 0; i < this.valuesInPixel.length; i++) {
      this.chart.ctx.beginPath();
      this.chart.ctx.moveTo(this.valuesInPixel[i].x1, this.valuesInPixel[i].y);
      this.chart.ctx.lineTo(this.valuesInPixel[i].x2, this.valuesInPixel[i].y);
      this.chart.ctx.strokeStyle = "#FF0000";
  
      this.chart.ctx.stroke();
    }
  }

  componentDidMount() {
    this.calculateValuesInPixel();
    this.drawHorizontalLines();
    window.addEventListener('resize', this.drawHorizontalLines );
  } 

  componentDidUnMount() {
    window.removeEventListener('resize', this.drawHorizontalLines );
  }
  .
  .
  .
}

Please check out this StackBlitz example for complete working code.

—-
Manoj Mohan
Team CanvasJS