xxxxxxxxxx
73
let colorA, colorB, colorC, black;
function setup() {
createCanvas(200, 200);
textSize(50);
colorA = color("#A95AA1");
colorB = color("#85C0F9");
colorC = color("#F5793A");
black = color("black");
}
function draw() {
background(240);
let origin = createVector(0, 0);
let a = createVector(mouseX, mouseY);
let b = createVector(-50, 40);
// Using the static method for addition:
let c = p5.Vector.add(a, b);
drawArrow(origin, a, colorA, 15);
drawArrow(a, b, colorB, 15);
drawArrow(origin, c, colorC, 15);
drawText();
}
function drawText() {
fill(colorC);
text("c", 20, 50);
fill(black);
text("=", 50, 55);
fill(colorA);
text("a", 85, 50);
fill(black);
text("+", 120, 55);
fill(colorB);
text("b", 155, 50);
}
// Draw an arrow representing a vector at a given base position.
function drawArrow(base, vec, myColor, arrowSize) {
push(); // Save current style settings & transformations.
// Copy the vector and limit it's length to
// account for the addition of the arrow head.
let drawVector = vec.copy();
drawVector.limit(vec.mag() - arrowSize);
// Set color and line thickness.
stroke(myColor);
fill(myColor);
strokeWeight(arrowSize/5);
// Move the 0,0 location to the base of the vector.
translate(base.x, base.y);
// Draw the vector line.
line(0, 0, drawVector.x, drawVector.y);
// Rotate to point in the direction of the vector.
rotate(drawVector.heading());
// Move the 0,0 location to the start of the arrow head.
translate(drawVector.mag(), 0);
// Draw the arrow head such that it points to the vector tip.
noStroke();
triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);
pop(); // Restore style settings & transformations.
}