Jump to content

  • Log In with Google      Sign In   
  • Create Account

Interested in a FREE copy of HTML5 game maker Construct 2?

We'll be giving away three Personal Edition licences in next Tuesday's GDNet Direct email newsletter!

Sign up from the right-hand sidebar on our homepage and read Tuesday's newsletter for details!






Very Basic JavaScript Game Code

Posted by Shippou, in JavaScript, HTML5 03 March 2014 · 413 views

JavaScript html5
The following is a very basic JavaScript game were you move a square around the screen. This script demonstrated how easy it is to set up your canvas and elements.
.
<html>
<center>
<canvas id="x" width="500" height="500" style="border:1px solid #000000;"></canvas> 
</center>
<script>
var c=document.getElementById("x");
var ctx=c.getContext("2d");
var FPS = 30;
var SPEED = 10;
var px = 200;
var py = 200;
var wx = 500;
var wy = 500;
setInterval(function(){
update();
draw();
},1000/FPS);
var textX = 50;
var textY = 50;
function update(){
key();
}
var player = {
color:"#00A",
width:32,
height:32,
draw: function(){
ctx.fillStyle = this.color;
ctx.fillRect(px,py,this.width,this.height);
}} ;

function draw(){
ctx.clearRect(0,0,wx,wy);
player.draw();
}
function key(){
var x = 0;
var y = 0;
document.onkeydown=function(e){
 var e=window.event || e 
  x = String.fromCharCode(e.keyCode);
  y = e.keyCode;
 //alert(x + " " + y );
if ( y == 38 && (py < wy && py > 0)){py -= SPEED; } // up
if ( y == 40 && (py < wy && py > 0)){ py += SPEED; } // down
if ( y == 37 && (px < wx && px > 0)){ px -= SPEED; } // left
if ( y == 39 && (px < wx && px > 0)){ px += SPEED; } // right

}
}
</script>
</html>





PARTNERS