Example 1.5
Vector Magnitude
Move mouse to interact with (magnitude is the width of rectangle) p5.js
function setup() {
createCanvas(560,390);
}
function draw() {
background(220);
// create two vectors, one for mouse location, one for the center of window
let mouse = createVector(mouseX,mouseY);
let center = createVector(width/2,height/2);
mouse.sub(center); // subtract vectors
// mag() is to calculate the magnitude of a vector
// the magnitude of a vector can be accessed via the mag() function
let magnitude = mouse.mag();
fill(63,63,147);
stroke(0);
rect(0,0,magnitude,10); //we use magnitude as width of a rectangle drawn at the top window
translate(width/2,height/2);
strokeWeight(2);
stroke(63,63,147);
line(0,0,mouse.x,mouse.y);
}