Skip to content

Instantly share code, notes, and snippets.

@maluramichael
Created November 12, 2014 12:53
Show Gist options
  • Save maluramichael/8f3692111bd96518d98f to your computer and use it in GitHub Desktop.
Save maluramichael/8f3692111bd96518d98f to your computer and use it in GitHub Desktop.
vector2
<html>
<body>
<canvas id='canvas' width='300' height='300'></canvas>
<script type="text/javascript">
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function( callback ){
window.setTimeout(callback, 1000 / 30);
};
})();
var ctx = document.getElementById('canvas').getContext('2d');
var t = 0;
function drawPoint(x,y){
ctx.fillStyle = "rgb(200,0,0)";
ctx.fillRect(x*32-4, y*32-4, 8, 8);
}
function radToDeg(rad){
return rad * (180 / Math.PI);
}
function degToRad(deg){
return deg * (Math.PI / 180);
}
function rotate(vector, angle) {
return {
x: vector.x + Math.cos(degToRad(angle)),
y: vector.y + Math.sin(degToRad(angle)),
}
}
function drawArc(x,y,r,s,e){
ctx.beginPath();
ctx.arc(x * 32, y * 32, r, s, radToDeg(e));
ctx.stroke();
}
function draw() {
ctx.clearRect(0,0,300,300);
var angle = t;
var origin = {x:2, y:2};
ctx.save();
ctx.translate(origin.x * 32, origin.y * 32);
ctx.rotate(degToRad(angle));
ctx.fillStyle = "rgb(200,0,0)";
ctx.fillRect(-4, -4, 8, 8);
ctx.restore();
var vector = rotate(origin, angle);
var direction = {x:vector.x - origin.x, y:vector.y - origin.y};
drawPoint(vector.x, vector.y);
drawArc(origin.x, origin.y, 32, 0, angle);
t += 1;
requestAnimFrame(draw);
}
draw();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment