当たり判定というか描画範囲を指定して,指定範囲以外に出ないようにしましょう.
サンプル
<!DOCTYPE html> <html> <head> <title>Key2</title> <meta charset="UTF-8"> </head> <body> <h1>Key2</h1> <canvas id="myCanvas" width="300" height="300" style="border:1px solid #000000;"></canvas> <script type="text/javascript"> var canvas = document.getElementById("myCanvas"); var context = canvas.getContext("2d"); var migi = false; var myX = 0; var myY = 0; var sokudo = 5; var aBool = false; var bBool = false; var cBool = false; var dBool = false; function kyesage(myEvt) { if (myEvt.keyCode == 39){ aBool = true; } if (myEvt.keyCode == 40){ bBool = true; } if (myEvt.keyCode == 38){ cBool = true; } if (myEvt.keyCode == 37){ dBool = true; } } function kyeageta(myEvt) { if (myEvt.keyCode == 39){ aBool = false; } if (myEvt.keyCode == 40){ bBool = false; } if (myEvt.keyCode == 38){ cBool = false; } if (myEvt.keyCode == 37){ dBool = false; } } document.onkeydown = kyesage; document.onkeyup = kyeageta; function draw() { context.clearRect(myX, myY, 20, 20); if(aBool == true){ if(myX < 280){ myX = myX + sokudo; } if(myX >= 280){ myX = 280; } } if(bBool == true){ if(myY < 280){ myY = myY + sokudo; } if(myY >= 280){ myY = 280; } } if(cBool == true){ if(myY <= 280){ myY = myY - sokudo; } if(myY < 0){ myY = 0; } } if(dBool == true){ if(myX <= 280){ myX = myX - sokudo; } if(myX < 0){ myX = 0; } } context.fillStyle = "#FF0000";//赤 context.fillRect(myX, myY, 20, 20); } setInterval(draw, 10); </script> </body> </html>
枠線との関係は理解できましたか?