JSFiddle - React, Tailwind, and code Playground
by madroller
HTML
<div id="canvas_container"><canvas id="my_canvas" width="1000" height="500"></canvas></div>
CSS
body{ background:#333; }
#canvas_container{ width:1000px; margin: 20px auto; }
#my_canvas{ background:#FFF; border:#999 1px solid; }
JavaScript
var bg = new Image();
bg.src = "http://globe-views.com/dcim/dreams/stars/stars-06.jpg";
window.requestAnimFrame = (function(callback) {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
function initCanvas(){
var ctx = document.getElementById('my_canvas').getContext('2d');
var cW = ctx.canvas.width, cH = ctx.canvas.height;
var dist = 3;
function Player(){
this.x = 0, this.y = 0, this.w = 50, this.h = 50;
this.render = function(){
ctx.beginPath();
ctx.arc(this.x, this.y, 10, 0, 2 * Math.PI, false);
ctx.fillStyle = "orange";
ctx.fill();
}
}
var player = new Player();
player.x = 100;
player.y = 225;
function animate(){
//ctx.save();
ctx.clearRect(0, 0, cW, cH);
player.render();
//ctx.restore();
requestAnimFrame(function() {
animate();
});
}
//var animateInterval = setInterval(animate, 30);
document.addEventListener('keydown', function(event) {
var key_press = String.fromCharCode(event.keyCode);
console.log(event.keyCode+" | "+key_press);
if(key_press == "W"){
player.y-=dist;
} else if(key_press == "S"){
player.y+=dist;
} else if(key_press == "A"){
player.x-=dist;
} else if(key_press == "D"){
player.x+=dist;
} else if(key_press == "F"){
player.x+=dist;
player.y+=dist*1.5;
}
});
requestAnimFrame(function() {
animate();
});
}
$(document).ready(function() {
initCanvas();
});