'Drawing a line that is an element of an array in p5.js

In my current p5.js project, I'm randomly plotting several lines on the canvas - so my background is in the setup function, but I wish to highlight the current one with a thicker stroke. In order to know which line was the last one drawn, I'm pushing them to a list to redraw just the last one later with a different stroke value. But I don't know how to display on the canvas such a line that is an element of an array. Somebody could help me?

What I have done so far:

//just inicializing the x-coordinates of the limit point of my line
let ax = 0;
let bx = 0;

//variables for the current line and the array of lines
let linha;
let linhas = [];

function setup() {
  createCanvas(400, 400);
  background(0);
}

function draw() {
  //randomly choosing the x-coordinates of the limit point of my line
  ax = random(0,400);
  bx = random(0, 400);
  
  
  stroke(255, 50)
  //plotting the current line
  linha = line(ax, 0, bx, 400);
  //putting it on the array
  linhas.push(line);
  
  
  //what I wish to be doing is something like
  /* 
  strokeWeight(5);
  'print' linhas(linhas.length - 1)  //where by print I mean display on the screen the last of the lines and only it, i.e. in the n+1 iteration, I don't want to have the n-line with that thicker stroke.
  */
  

}


Solution 1:[1]

Something like below will help. I've added comments on the relevant lines.

//just saving the indices for better readibility and to make it less bug-prone.
const x = 0,
  start = 0,
  y = 1,
  end = 1;

const myLines = [];

function setup() {
  createCanvas(400, 400);

  //move the entire codeblock below to draw() if you randomize it on every render.
  //add your random lines as such
  myLines.push([[10, 20],[30, 40]]);
  myLines.push([[20, 20],[20, 60]]);
  myLines.push([[30, 20],[10, 300]]);
  myLines.push([[40, 20],[100, 120]]);
  myLines.push([[50, 20],[40, 80]]);
  
  background(220);
  //drawing the lines from the array
  for (let i = 0; i < myLines.length; i++) {
    line(
      myLines[i][start][x],
      myLines[i][start][y],
      myLines[i][end][x],
      myLines[i][end][y]
    );
  }
  
  //getting the last element in the array to draw a thicker line
  strokeWeight(5);
  line(
      myLines[myLines.length - 1][start][x],
      myLines[myLines.length - 1][start][y],
      myLines[myLines.length - 1][end][x],
      myLines[myLines.length - 1][end][y]
    );
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1