Drawing lines using vectors in p5.js
The regular p5.js line()
method expects four arguments: x1
, y1
, x2
, and y2
.
Because I have found myself drawing lines between points quite a lot recently, I made a tiny wrapper function for myself. It takes two objects as arguments and passes their x
and y
values to line()
. This means that instead of having to write line(foo.x, foo.y, bar.x, bar.y)
I can use vLine(foo, bar)
, which is easier to read and faster to type.
function vLine(a, b) {
line(a.x, a.y, b.x, b.y)
}
The arguments given to vLine()
could be p5.Vector objects made using createVector()
, or any object with x
and y
properties. For example:
setup() {
createCanvas(100, 100)
const pointA = createVector(width/2, height/2)
const pointB = { x: random(width), y: random(height) }
vLine(pointA, pointB)
}