Last active
February 18, 2018 04:31
-
-
Save sabha/194002fb82408f65b666ae3aa526a30b to your computer and use it in GitHub Desktop.
Vector
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<body> | |
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;"> | |
Your browser does not support the HTML5 canvas tag.</canvas> | |
<script> | |
var mouseX = 0; | |
var mouseY = 0; | |
window.vector = class vector { | |
constructor(x,y) { | |
this.x = x; | |
this.y = y; | |
} | |
add(vec){ | |
this.x += vec.x; | |
this.y += vec.y; | |
} | |
sub(vec){ | |
this.x -= vec.x; | |
this.y -= vec.y; | |
} | |
div(v){ | |
this.x /= v; | |
this.y /= v; | |
} | |
mul(v){ | |
this.x *= v; | |
this.y *= v; | |
} | |
mag(){ | |
return(Math.sqrt((this.x * this.x) + (this.y * this.y))); | |
} | |
normalize(){ | |
var mag = this.mag(); | |
this.div(mag); | |
} | |
setMag(v) { | |
this.normalize(); | |
this.mul(v); | |
} | |
limit(v){ | |
if(this.mag() >= v) { | |
this.setMag(v); | |
} | |
} | |
} | |
var c = document.getElementById("myCanvas"); | |
var ctx = c.getContext("2d"); | |
var loc = new vector(c.width/2, c.height/2); | |
var vel = new vector(0,0); | |
var acc = new vector(0,0); | |
function line(vec){ | |
ctx.moveTo(0,0); | |
ctx.lineTo(vec.x,vec.y); | |
} | |
function render() { | |
ctx.clearRect(0, 0, 300, 150); | |
ctx.beginPath(); | |
var mouse = new vector(mouseX,mouseY); | |
console.log(loc, mouse); | |
mouse.sub(loc); | |
mouse.setMag(1); | |
acc = mouse; | |
console.log(mouse); | |
vel.add(acc); | |
loc.add(vel); | |
vel.limit(10); | |
console.log(vel, loc); | |
ctx.arc(loc.x,loc.y,2,0,2*Math.PI); | |
ctx.stroke(); | |
ctx.closePath(); | |
} | |
c.addEventListener('mousemove', function(evt) { | |
var rect = c.getBoundingClientRect(); | |
mouseX = evt.clientX - rect.left, | |
mouseY = evt.clientY - rect.top | |
}, false); | |
setInterval(render, 100); | |
</script> | |
<p><strong>Note:</strong> The canvas tag is not supported in Internet | |
Explorer 8 and earlier versions.</p> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment