Primitives Shapes - line

line()

The line() function takes 4 arguments. 

These are: x1, y1, x2, y2. Thus we have line ( x1,y1,x2,y2).

The x1 parameter is the x-coordinate of the first point whereas the x2 is the one of the last point.

The y1 parameter is the y-coordinate of the first point whereas the y2 is the one of the last point.

Let's see an example of a code that uses the line() function to create an abstract shape:

function setup() {
  // create canvas
  createCanvas(800,500);
  // set background color
  background('orange');
}
function draw () {
  line ((width/2-100),height/2, (width/2+100),height/2);
  line ((width/2-100),height/2,(width/2-200),150);
  line ((width/2+100),height/2,(width/2+200),350);
}

Can you imagine what would be the outcome of the above code?

Result of the above code:

Exercise

  1. Open your Visual Studio editor and the p5yourName folder.
  2. Open the file ex812.js in your editor and save it as ex824.js
  3. Open the file ex812.html in your editor and save it as ex824.html
  4. In the ex824.html file, update the link to ex824.js  from ex812.js
  5. Go to the index.html file and create, under Module 8, a link to the ex824.html  file with the title "Primitives Shapes - line".

Modify the ex824.jsfile in order to create a staircase using lines. You can see here an example.

Answer:

let i = 20;
function setup() {
  // create canvas
  createCanvas(800,500);
  // set background color
  background('orange');
}
function draw () {
  // left line
  line (350,100, 350,300);
  // right line
  line (450,100, 450,300);
  // draw horizontal lines across the height of the two vertical lines
  for (i; i<200; i= i+20){
    line (350,100+i, 450,100+i);
  }
}

Do a Git commit with the message "Primitives Shapes - line".

  • See more about the line() function