xxxxxxxxxx
99
/*
ABOUT
In this sketch, we can define a custom graphing window, with a custom
origin and a custom scale for each axis.
For example, we can create a graphing window with its origin in the
center of the canvas, and with ten pixels per unit on both axes.
(We could use different scales on each axis if we want.) We can call
our graphing window whatever we want. Let's call it g.
To plot a point at the origin in this coordinate system, we can type
g.point(0,0), instead of point(width / 2, height / 2). Other shapes
can also be drawn in the same way, by specifying coordinates directly
in the custom coordinate system.
Right now, only a few custom math shapes are provided: arrows, very
basic axes, and tick marks. The only p5.js primitive that's been
adapted is point(), so g.point() works, but g.line() and similar
commands don't work yet.
The code below gives working examples of all the features that are
supported. The code that makes it all work is in graphWindow.js,
which you can find in the directory for this project.
Note: The design and implementation may not be suitable for
generalization. I put it together quickly.
*/
let xOrigin;
let yOrigin;
let xScale; //px per unit
let yScale; //px per unit
let graphWindow;
let z, v, w, r; //vectors (p5.Vector objects)
//colors (putting these here for convenience)
let myMagenta, myGreen, myOrange;
function setup() {
createCanvas(400, 400);
//colors
myMagenta = color(200, 0, 200);
myGreen = color(0, 245, 0);
myOrange = color(252, 152, 0);
//Create graph window
xOrigin = width / 2;
yOrigin = height / 2;
xScale = 10; //px per unit
yScale = 10; //px per unit
graphWindow = createGraphWindow(xOrigin, yOrigin, xScale, yScale);
//vectors
v = createVector(5, 12);
w = createVector(5, 3);
r = p5.Vector.add(v, w); //'r' for resultant vector
z = createVector(0, 0); //'z' for zero vector
//component vectors
v1 = createVector(v.x, 0);
v2 = createVector(0, v.y);
}
function draw() {
background(240, 240, 240);
//Axes, ticks
strokeWeight(2);
stroke(0, 0, 0);
graphWindow.axis('horizontal'); //draw x-axis
graphWindow.tick('horizontal', r.x); //draw tick on x-axis at r.x
graphWindow.axis('vertical'); //draw y-axis
graphWindow.tick('vertical', r.y); //draw tick on y-axis at r.y
//Point
strokeWeight(12);
stroke(0, 0, 255);
graphWindow.point(r.x, r.y); //draw point at graph coords r.x, r.y
//Arrows
strokeWeight(3);
stroke(myGreen);
graphWindow.arrow(w, v); //draw w at v
stroke(myOrange);
//arrow head width, height = 0 => no head
graphWindow.arrow(v1, z, 0, 0); //horizontal component
graphWindow.arrow(v2, v1, 0, 0); //vertical component
stroke(myMagenta);
graphWindow.arrow(v); //same as graphWindow.arrow(v, z), i.e.
//if left unspecified,
//the point at which v is drawn defaults
//to the origin
}