xxxxxxxxxx
96
function setup() {
createCanvas(400, 400);
textSize(20);
}
function draw() {
background(250);
let gridStep = 40;
let origin = createVector(width / 2, height / 2);
let mousePosition = createVector(mouseX, mouseY);
let vector = mousePosition.sub(origin);
drawGrid(gridStep);
drawArrow(origin, vector, color("red"), 20);
drawText(vector, gridStep);
}
// Draw the vector head location in (x, y) format
// in the top right corner of the canvas.
function drawText(vector, gridStep) {
// The x value is our pixel position divided
// by the grid step size.
let xValue = (vector.x / gridStep).toFixed(2);
// y needs to be negated since the p5.js direction
// of y is flipped from the usual cartesian direction.
let yValue = (-vector.y / gridStep).toFixed(2);
text(`(${xValue}, ${yValue})`, 280, 27);
}
// Draw the 2D cartesian grid.
function drawGrid(gridStep) {
push(); // Save all current drawing style settings.
// Unit grid lines will be light grey.
stroke(200);
strokeWeight(1);
// Draw vertical unit grid lines.
for (let i = 0; i <= width / gridStep; i++) {
line(gridStep * i, 0, gridStep * i, height);
}
// Horizontal unit grid lines.
for (let i = 0; i <= height / gridStep; i++) {
line(0, gridStep * i, width, gridStep * i);
}
// Axis lines will be black and slightly thicker.
stroke(0);
strokeWeight(2);
// Draw x-axis.
line(0, height / 2, width, height / 2);
// Draw y-axis.
line(width / 2, 0, width / 2, height);
pop(); // Restore saved drawing style settings.
}
// 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.
}