playing with vectors

by Darby Rathbone

HTML

<div id='show'></div>
<canvas id='can' width=400 height=400></canvas>

CSS

canvas { border: 1px solid black; }

JavaScript

function returnVector(x, y, c) {
  return {
    x: x,
    y: y,
    c: c ? c : 1
  };
}

function normalizeVector(v) {
  var x = v.x,
    y = v.y,
    c = Math.sqrt(x * x + y * y);
  return returnVector(x / c, y / c, c * v.c);
}

function addVector(a, b) {
  return normalizeVector(returnVector(a.x + b.x, a.y + b.y));
}

function subVector(a, b) {
  return normalizeVector(returnVector(a.x - b.x, a.y - b.y));
}

function drawVector(context, v, color) {
  var n = normalizeVector(v);
  context.strokeStyle = color;
  context.beginPath();
  context.moveTo(context.canvas.width / 2, context.canvas.height / 2);
  context.lineTo(n.x * 50 * v.c + context.canvas.width / 2, n.y * 50 * v.c + context.canvas.height / 2);
  context.closePath();
  context.stroke();

}
var test = returnVector(1, 1);
var show = document.getElementById("show");
var can = document.getElementById("can"),
  ctx = can.getContext("2d");
var wall = returnVector(10, 10),
  move = returnVector(-5, 2);

//console.log(ctx.canvas);
drawVector(ctx, wall, "red");
drawVector(ctx, move, "green");
move = normalizeVector(move);
wall = normalizeVector(wall);
test = addVector(wall, move);
var test2 = subVector(move, wall);
drawVector(ctx, test2, "yellow");
console.log(test);
show.innerText = JSON.stringify(test) + JSON.stringify(wall) + JSON.stringify(move);
drawVector(ctx, test, "blue");