So this is my code:
document.onkeydown = checkKey;
function checkKey(e) {
e = e || window.event;
if (e.keyCode == '38') {
}
else if (e.keyCode == '40') {
console.log("Down Arrow");
g.rect( 200,200,20,20); << Here is the problem. This is ignored.
}
else if (e.keyCode == '37') {
// left arrow
}
else if (e.keyCode == '39') {
// right arrow
}
}
rect( snake.X,snake.Y,20,20 );
I want the code to change the position of the block on the canvas, but all the Down arrow does when I push it is Write in the console, "Down Arrow." It will not display a rectangle at X: 200 Y: 200. Can somebody help? I am doing this for a snake game.
You need to tell your program to draw the rectangle you have specified with the command ctx.stroke();
. An example is shown in the snippet below, you need to click on the iframe and then press the down arrow for it to be registered.
Let me know if this doesn't work.
document.onkeydown = checkKey;
function checkKey(e) {
e = e || window.event;
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
if (e.keyCode == '38') {
}
else if (e.keyCode == '40') {
console.log("Down Arrow");
ctx.rect( 10,10,20,20);
ctx.stroke();
}
else if (e.keyCode == '37') {
// left arrow
}
else if (e.keyCode == '39') {
// right arrow
}
}
.box {
height: 100px;
width: 100px;
border: 1px solid black;
}
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;">
</canvas>