Published
Edited
Nov 8, 2021
Insert cell
Insert cell
import {p5, P5} from "@tmcw/p5";
Insert cell
p5(sketch => {

let v0, v1, v2, v3;
let a1, a2, a3;

sketch.setup = function() {
sketch.createCanvas(400, 300);
sketch.background(240);

v0 = sketch.createVector(sketch.width/2, sketch.height/2);
v1 = sketch.createVector(70, 70);
v2 = sketch.createVector(70, -30);
// The solution. Use P5 instead of p5 for static functions
v3 = P5.Vector.sub(v1, v2);
a1 = new Arrow(sketch, v0.x, v0.y, v1.x, v1.y);
a2 = new Arrow(sketch, v0.x, v0.y, v2.x, v2.y);

//subVec();
a3 = new Arrow(sketch, v0.x + v2.x, v0.y + v2.y, v3.x, v3.y); // v2 coordinates are added to v0 to shift the arrow's beggining to v2
}

sketch.draw = function() {
a1.display('blue');
a2.display('red');
a3.display('green');

}
// function subVect() leaved here just for reference.
/*
function subVec() {
v3 = p5.Vector.sub(v1, v2);
console.log(v3);
sketch.redraw();
}*/
})
Insert cell
class Arrow {
constructor(p5, x1, y1, x2, y2) {
this.p5 = p5;
this.point1 = this.p5.createVector(x1, y1);
this.point2 = this.p5.createVector(x2, y2);
}
display(myColor) {
this.p5.push(); // Start a new drawing state regarding fill, stroke, translate, etc
this.p5.stroke(myColor);
this.p5.strokeWeight(3);
this.p5.fill(myColor);
this.p5.translate(this.point1.x, this.point1.y);
this.p5.line(0, 0, this.point2.x, this.point2.y);
// Draw an arrow
this.p5.rotate(this.point2.heading());
let arrowSize = 7;
this.p5.translate(this.point2.mag() - arrowSize, 0);
this.p5.triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);
this.p5.pop(); // Restore original drawing state
}
}

Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more