Vector class
by djwelsh
HTML
<canvas id="djw-canvas" width="400" height="600"></canvas>
<div id="djw-options"></div>
<div id="djw-debug"></div>
CSS
canvas {
outline: 1px solid #333;
}
label {
display: block;
}
JavaScript
//obj contains just dx and dy (and peripheral info later, such as custom anchors)
function Vector (obj) {
this.dx = obj.dx;
this.dy = obj.dy;
this.anchor = {
x : 0,
y : 0
};
}
Vector.prototype.setAnchor = function (obj) {
this.anchor.x = obj.x;
this.anchor.y = obj.y;
};
//Draws a vector from the coordinates given using the context provided
Vector.prototype.draw = function(context, color) {
var x = this.anchor.x;
var y = this.anchor.y;
context.strokeStyle = color;
context.fillStyle = color;
context.lineWidth = 2;
context.beginPath();
context.moveTo(x, y);
context.arc(x, y, 4, 0, Math.PI * 2);
context.fill();
context.moveTo(x, y);
context.lineTo(x + this.dx, y + this.dy);
context.stroke();
context.moveTo(x + this.dx, y + this.dy);
context.arc(x + this.dx, y + this.dy, 3, 0, Math.PI * 2);
context.fill();
context.beginPath();
context.fillStyle = "#fff";
context.moveTo(x, y);
context.arc(x, y, 3, 0, Math.PI * 2);
context.fill();
};
Vector.prototype.magnitude = function () {
return Math.sqrt(this.dx * this.dx + this.dy * this.dy);
};
Vector.prototype.endPoint = function () {
return {
x: this.anchor.x + this.dx,
y: this.anchor.y + this.dy
};
};
//Bool copy keeps vector as is and returns a new, normalized one if true
Vector.prototype.normalize = function (copy) {
if (copy) {
return new Vector({ dx : this.dx / this.magnitude(), dy : this.dy / this.magnitude() });
}
else {
this.dx /= this.magnitude();
this.dy /= this.magnitude();
}
};
//Get the vector perpendicular to this one, to the left or right
Vector.prototype.normal = function (right, copy) {
if (copy) {
return new Vector({ dx : this.dy * (right ? -1 : 1), dy : this.dx * (right ? 1 : -1) });
}
else {
this.dx = this.dy * (right ? -1 : 1);
this.dy =...