Skip to content

Instantly share code, notes, and snippets.

@NotJustAnna
Created February 6, 2019 23:04
Show Gist options
  • Save NotJustAnna/e8fd097bd43fc4dc829cef38b224e7b9 to your computer and use it in GitHub Desktop.
Save NotJustAnna/e8fd097bd43fc4dc829cef38b224e7b9 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<title>2D</title>
<meta charset="UTF-8">
<style>
body, canvas, html { margin:0; padding:0; border:0 none; }
canvas { display: block; cursor: none; }
</style>
</head>
<body>
<script>
var w = window.innerWidth;
var h = window.innerHeight;
var canvas = document.createElement("canvas");
canvas.width = w;
canvas.height = h;
document.body.appendChild(canvas);
var ctx = canvas.getContext("2d");
var prevTime = 0;
var timeDelta = 0;
function loop(time) {
timeDelta = time - prevTime;
prevTime = time;
// Process input
// Update game world
gameObj.update(timeDelta);
// Draw
ctx.fillStyle = "#000000";
ctx.fillRect(0, 0, w, h);
mouseObj.draw(ctx);
gameObj.draw(ctx);
// Repeat
window.requestAnimationFrame(loop);
}
var gameObj = {
x: 0,
y: h / 2,
xVel: 0,
yVel: 0,
radius: 20,
color: "#ff0000",
update: function (timeDelta) {
var dirX = mouseObj.x - this.x;
var dirY = mouseObj.y - this.y;
var len = Math.sqrt(dirX * dirX + dirY * dirY);
dirX = dirX / len;
dirY = dirY / len;
this.xVel = dirX * 0.2;
this.yVel = dirY * 0.2;
this.x += this.xVel * timeDelta;
this.y += this.yVel * timeDelta;
},
draw: function (ctx) {
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.fill();
}
};
var mouseObj = {
x: 0,
y: 0,
draw: function (ctx) {
ctx.drawImage(catImg, this.x - 64, this.y - 64, 128, 128);
}
}
canvas.onmousemove = function (event) {
mouseObj.x = event.clientX;
mouseObj.y = event.clientY;
}
var catImg = new Image();
catImg.src = "https://upload.wikimedia.org/wikipedia/commons/3/3c/Creative-Tail-Animal-cat.svg";
catImg.onload = function () {
window.requestAnimationFrame(loop);
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment