xxxxxxxxxx
51
// Demo code for my blog at https://arnauld-alex.com/
let vectorA;
let magnitudeA;
const xShift = 100;
const yShift = 50;
function setup() {
createCanvas(400, 200);
vectorA = createVector(200, 100)
magnitudeA = vectorA.mag();
console.log(`Magnitude of vector A: ${magnitudeA}`);
}
function draw() {
background(2, 6, 23);
drawVector(vectorA, 'A', color(255));
drawComponents(vectorA);
fill(255);
noStroke();
textSize(16);
text(`|A| = ${magnitudeA.toFixed(2)}`, 20, height - 20);
}
function drawVector(vector, label, col) {
stroke(col);
strokeWeight(4);
line(xShift, yShift, xShift + vector.x, yShift + vector.y);
strokeWeight(1);
fill(col);
text(label, xShift + vector.x + 10, yShift + vector.y - 5);
strokeWeight(8);
point(xShift + vector.x, yShift + vector.y);
}
function drawComponents(vector) {
stroke(255, 0, 0);
strokeWeight(2);
line(xShift, yShift, xShift + vector.x, yShift);
line(xShift + vector.x, yShift, xShift + vector.x, yShift + vector.y);
fill(255, 0, 0);
noStroke();
text(`x: ${vector.x}`, xShift + vector.x / 2 - 20, yShift - 10);
text(`y: ${vector.y}`, xShift + 10 + vector.x, yShift + vector.y / 2);
}