A vector is a directed segment defined by its magnitude and direction. Unlike scalar quantities, which have only a value, vectors describe both how much and in which direction something “pushes” or “moves.” See examples and operations on vectors in our detailed guide at SvetProgramiranja: Vector Operations .
Below is an interactive p5.js example showing two random vectors in the plane. Click and drag the arrowheads to reposition them and see how they change.
This simulation uses the p5.js library to draw two draggable vector arrows. The canvas is 600×400 pixels, and we shift the coordinate origin to the center.
Global variables:
vectors
— array of objects, each with vx, vy
and a color col
.dragging
— reference to the currently dragged vector (or null
).setup():
createCanvas(600, 400)
and canvas.parent('sketch-holder')
attach it to HTML.vectors.push({ vx: ..., vy: ..., col: ... });
draw():
background(240)
clears the canvas.line(width/2, 0, width/2, height); line(0, height/2, width, height/2);
drawVector(v)
which:
line(0, 0, vx, –vy)
triangle()
ellipse()
Interaction:
mousePressed()
— checks if you clicked within 10px of an arrowhead and sets dragging
.mouseDragged()
— while dragging, updates dragging.vx
and dragging.vy
.mouseReleased()
— clears dragging
, ending the drag.
// main array and variable for dragging
let vectors = [];
let dragging = null;
function setup() {
const canvas = createCanvas(600, 400);
canvas.parent('sketch-holder');
// Generate two random vectors
for (let i = 0; i < 2; i++) {
vectors.push({
vx: random(-150, 150),
vy: random(-100, 100),
col: i === 0 ? '#e63946' : '#2a9d8f'
});
}
}
function draw() {
background(240);
stroke(50);
// draw axes through the center
line(width/2, 0, width/2, height);
line(0, height/2, width, height/2);
noStroke();
// display each vector
vectors.forEach(v => {
drawVector(v);
});
}
function drawVector(v) {
push();
translate(width/2, height/2);
stroke(v.col);
strokeWeight(3);
line(0, 0, v.vx, -v.vy);
// arrowhead
push();
translate(v.vx, -v.vy);
rotate(-atan2(v.vy, v.vx));
fill(v.col);
noStroke();
triangle(0, 0, -10, 5, -10, -5);
pop();
// handle for dragging
noStroke();
fill(v.col);
ellipse(v.vx, -v.vy, 12);
pop();
}
function mousePressed() {
const mx = mouseX - width/2;
const my = -(mouseY - height/2);
for (let v of vectors) {
if (dist(mx, my, v.vx, v.vy) < 10) {
dragging = v;
break;
}
}
}
function mouseDragged() {
if (dragging) {
dragging.vx = mouseX - width/2;
dragging.vy = -(mouseY - height/2);
}
}
function mouseReleased() {
dragging = null;
}
In this brief video, we explain how to use the interactive practice app for vector operations. Here is a concise summary of the steps:
For more detailed instructions, examples, and theoretical explanations, watch the video: