Forum Moderators: open
<html>
<div style='background-color:blue; height:480px; width:640px;'>
<canvas id="gameCanvas" width="640" height="480"></canvas>
</div>
<script>
var ctx=gameCanvas.getContext("2d");
var x=240, y=180, dir=90, score=0;
drawBackground();
function drawBackground(){
ctx.strokeStyle='orange';
ctx.lineWidth=40;
ctx.strokeRect(0, 0, 640, 480);
}
var gameTimer=setInterval(mainLoop, 50);
function mainloop(){
ctx.fillstyle='orange';
ctx.fillRect(x,y,9,9);
if(dir==90){x+=10;}
if(dir==180){y+=10;}
if(dir==-90){x-=10;}
if(dir==0){y-=10;}
//checkpixelcolor();
score++;
ctx.fillRect(0,0,100,20);
ctx.fillStyle='black';
ctx.font="20px Arial";
ctx.fillText("Score: "+score,2,16);
}
function checkPixelcolor(){
var col=ctx.getImagedata(x,y,1,1).data;
if(col[3]!=0){
clearInterval(gameTimer);
ctx.font="80px Arial";
ctx.fillText("Game Over!",100,250);
}
}
</script>
<html>
gameCanvas is not defined
It's automatically defined by the use of id="gameCanvas". Not as foolproof as getElementById() or querySelector(), but it works.
[edited by: futureautomation at 10:28 am (utc) on May 4, 2022]
I used this code from a recent published book.
No idea on what is up with this one, another code example from the book.
What I meant, is I typed it out of the book I have, ...
There were a few errors, I did type it as the tutorial stated, there are errors in the code of the book, almost beginner mistakes. That isn't good editing.
...this book should help me understand some javascript, having errors in certain places is no good to a beginner.
The unfortunate position about the company that sells the book, is they offer no support for any of the tutorials. So a book is published with some errors, and no support is offered. Cheap rip off.
Sure, but the code in the book should work as is, why would there be errors, MainLoop is a consistent error in the book, and this is aimed at a beginner audience, of those under sixteen, anybody within that age range. It shouldn't have these errors, if you are new, a beginners book with basic examples should be accurate.
I think from a beginner's view that type of example isn't good, it may as a tutorial which gives the example of poor code or broken code, but sort of blindly, I think a few would be scratching their head, wondering what is going on here. In another one of those books, poor code was used for an image upload. I got a view from another forum a few years back, and the poster stated the code was rubbish, and the author should've made sure to check what they produce so that it works.
The game book probably needs updating on errors, and so on, to give a pointer.