I've got this issue with the canvas not being written to the browser, I'm following a w3schools tutorial to build a basic game.
I'm wondering why the body-block isn't growing given the placement of the canvas in the style tag. The javascript is an external file, the dimensions of the canvas tag are specified there.
There should be the thread for the CSS calls and a thread for the HTML/Javascript calls, where and why is this code not defining a block for my canvas?
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</head>
<body>
<style>
canvas {
border:1px solid #d3d3d3;
background-color: #f1f1f1;
}
</style>
<script type="text/javascript" src="/Users/cgoodwin/game/g.js">
window.onload = start;
</script>
</body>
</html>
The above is the HTML document
Below is the JS
function start(){
gameArea.start();
}
var gameArea={
canvas:document.createElement("canvas"),
start:function(){
this.canvas.width=480;
this.canvas.height=270;
this.context=this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.interval=setInterval(update,20);
},
clear:function(){
this.context.clearRect(0,0,this.canvas.width,this.canvas.height);
}
}
var gamePiece;
function start(){
gameArea.start();
gamePiece=new component(30,30,"red",10,120);
}
function component(width,height,color,x,y){
this.width=width;
this.height=height;
this.x=x;
this.y=y;
this.update=function(){
ctx=gameArea.context;
ctx.fillStyle=color;
ctx.fillRect(this.x,this.y,this.width,this.height);
}
}
function updateGameArea(){
gameArea.clear();
gamePiece.x += 1;
gamePiece.update();
}
I added a "Watch Expression" with the developer tools on the gamePiece and it's saying it isn't defined. Likely, that's my issue, but why isn't it being defined? It could be that the game updating triggers it to be undefined in any given instance, adding a watch might not work when evaluating something that is being cleared and changed every 20 milliseconds.