对象使用html5和javascript通过键盘箭头键移动

时间:2013-07-19 13:32:19

标签: javascript html5-canvas

如何使用html5和javascript使用键盘键移动对象。在这里,我尝试使用下面的代码,但它没有移动可以任何人帮助使用键盘箭头键移动对象?

<!DOCTYPE html>  
<html>  
<head>
</head>
<body onLoad="gameLoop()" onkeydown="keyDown(event)" onkeyup="keyUp(event)" bgcolor='green'>  
<canvas id="mycanvas"></canvas>    
<script>  
var canvas = document.getElementById('mycanvas');  
var ctx = canvas.getContext('2d');  
ctx.beginPath();  
ctx.arc(100, 100, 50, 0.25 * Math.PI, 1.25 * Math.PI, false);  
ctx.fillStyle = "rgb(255, 255, 0)";  
ctx.fill();  
ctx.beginPath();  
ctx.arc(100, 100, 50, 0.75 * Math.PI, 1.75 * Math.PI, false);  
ctx.fill();  
ctx.beginPath();  
ctx.arc(100, 75, 10, 0, 2 * Math.PI, false);
  ctx.fillStyle = "rgb(0, 0, 0)";  
ctx.fill();  
//moves//  
var xpos=500;  
var ypos=550;  
var xspeed=1;  
var yspeed=0;  
var maxspeed=5;  
//boundaries//  
var minx=500;  
var miny=200;  
var maxx=990;  
var maxy=400;  
//controller   
var upPressed=0;   
var downPressed=1;  
var leftPressed=0;  
var rightPressed=0;   
function slowDownX()  
{  
 if(xspeed > 0) xspeed=xspeed-1;  if(xspeed<0)  xspeed=xspeed+1;
  }  
function slowDownY()  
 {  
if(yspeed > 0)
  yspeed = yspeed-1;  
if(yspeed < 0)  
yspeed = yspeed+1;
  }  
function gameLoop()  
{  
xpos=Math.min(Math.max(xpos+xspeed,minx),maxx);   ypos=Math.min(Math.max(ypos+yspeed,miny),maxy);  
xpos = document.getElementById('mycanvas').style.left;  
ypos = document.getElementById('mycanvas').style.top;  
if (upPressed == 1)  
yspeed = Math.max(yspeed - 3,-3*maxSpeed);  
if (downPressed == 1)  
yspeed = Math.min(yspeed + 3,3*maxSpeed)  
if (rightPressed == 1)  
xspeed = Math.min(xspeed + 1,1*maxSpeed);  
if (leftPressed == 1)  
xspeed = Math.max(xspeed - 1,-1*maxSpeed);  
if (upPressed == 0 && downPressed == 0)  
slowDownY();  
if (leftPressed == 0 && rightPressed == 0)  
slowDownX();  
return setTimeout("gameLoop()",10);  
}  
function keyDown(e)  
{  
var code = e.keyCode ? e.keyCode : e.which;  
if (code == 38)  
upPressed = 1;  
if (code == 40)  
downPressed = 1;  
if (code == 37)  
leftPressed = 1;  
if (code == 39)  
rightPressed = 1;  
}  
function keyUp(e)  
{  
var code = e.keyCode ? e.keyCode : e.which;  
if (code == 38)  
upPressed = 0;  
if (code == 40)  
downPressed = 0;  
if (code == 37)  
leftPressed = 0;  
if (code == 39)  
rightPressed = 0;  
}  
</script>  
</body>  
</html>

2 个答案:

答案 0 :(得分:6)

以下是在html画布上绘制形状并使用箭头键移动它的基础知识

免责声明:此代码不是最好的游戏技巧,它意味着明确的指令。 ;)

首先创建一些定义球的变量:

    // the ball will be at coordinates 70,75

    var ballX=70;
    var ballY=75;

    // the ball will have a radius of 15;

    var ballRadius=15;

接下来创建一个将在指定坐标

处绘制球的函数
    function draw(){

        // clear the canvas for the next frame

        ctx.clearRect(0,0,canvas.width,canvas.height);

        // draw a ball that the use can move with left/right arrow keys
        // the ball's center will be at BallX / BallY
        // the ball will have a radius of BallRadius

        ctx.beginPath();
        ctx.arc(ballX,ballY,ballRadius,0,Math.PI*2,false);
        ctx.closePath();
        ctx.fill();

    }

现在听用户的击键。

    // Listen for when the user presses a key down

    window.addEventListener("keydown", keyDownHandler, true);

当用户按下某个键时:

  • 如果用户按下左箭头或右箭头,请通过更改它的“ballX”坐标来移动球。
  • 更改球​​位置后,重绘画布

此代码处理密钥关闭时(由addEventListener调用):

    // Here we just handle command keys
    function keyDownHandler(event){

        // get which key the user pressed
        var key=event.which;

        // Let keypress handle displayable characters
        if(key>46){ return; }

        switch(key){
            case 37:  // left key

              // move the ball 1 left by subtracting 1 from ballX
              ballX -= 1;

              break;

            case 39:  // right key

              // move the ball 1 right by adding 1 to ballX
              ballX += 1;

              break;

            default:
              break;
        }

        // redraw the ball in its new position
        draw();

    }

这是代码和小提琴:http://jsfiddle.net/m1erickson/TsXmx/

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>

<style>
    body{ background-color: ivory; padding:20px;}
    #canvas{border:1px solid red;}
</style>

<script>
$(function(){

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");

    ctx.strokeStyle="blue";
    ctx.fillStyle="red";

    var ballX=70;
    var ballY=75;
    var ballRadius=15;

    var leftWall=30;
    var rightWall=120;

    draw();

    function draw(){

        // clear the canvas for the next frame
        ctx.clearRect(0,0,canvas.width,canvas.height);

        // tell canvas to start a new path

        // draw walls on left and right
        ctx.beginPath();
        ctx.moveTo(leftWall,0);
        ctx.lineTo(leftWall,canvas.height);
        ctx.moveTo(rightWall,0);
        ctx.lineTo(rightWall,canvas.height);
        ctx.lineWidth=2;
        ctx.stroke();

        // draw a ball that the use can move with left/right arrow keys
        ctx.beginPath();
        ctx.arc(ballX,ballY,ballRadius,0,Math.PI*2,false);
        ctx.closePath();
        ctx.fill();
    }


    // Here we just handle command keys
    function keyDownHandler(event){

        // get which key the user pressed
        var key=event.which;

        // Let keypress handle displayable characters
        if(key>46){ return; }

        switch(key){
            case 37:  // left key

              // move the ball 1 left by subtracting 1 from ballX
              ballX -= 1;

              // calc the ball's left edge
              var ballLeft=ballX-ballRadius;

              // Keep the ball from moving through the left wall
              if(ballLeft<=leftWall){ ballX=leftWall+ballRadius; }

              break;

            case 39:  // right key

              // move the ball 1 right by adding 1 to ballX
              ballX += 1;

              // calc the ball's right edge
              var ballRight=ballX+ballRadius;

              // Keep the ball from moving through the right wall
              if(ballRight>=rightWall){ ballX=rightWall-ballRadius; }

              break;

            default:
              break;
        }

        // redraw everything
        draw();

    }

    // Listen for when the user presses a key down
    window.addEventListener("keydown", keyDownHandler, true);


}); // end $(function(){});
</script>

</head>

<body>
    <p>Click in the red box to get keyboard focus</p>
    <p>Then Move ball with left and right arrow keys</p>
    <canvas id="canvas" width=200 height=150></canvas>
</body>
</html>

答案 1 :(得分:0)

两个球是移动差异。在键盘上。

  1. 第一个球移动到键盘上,下,右,左键
  2. 第二球移动到A(左侧),W(上侧),D(右侧)和S(下侧)。
  3. 只需在屏幕上复制并过去。

    <html>
    <head>
    <title> game</title>
    </head>
    <body>
    <canvas id="canvas" width="307" height= "211" style= "border:1px solid #ff0000 ;" mxrgin = right >
    </canvas>
    <script>
    
    var x = 10;
    var x1= 280;
    var y = 10;
    var y1 = 10;
    var dx = 2;
    var dx1 = 3;
    var dy = 1;
    var dy1 =1;
    var ctx;
    var ctx1;
    var WIDTH=300; 
    var HEIGHT=200;
    var a="";
    var b="";
    var sp= 500;
    var timer=[];
    
    var down = [];
    var up;
    document.onkeydown=k_down;
    document.onkeyup=k_up;
    var left=false;
    var right=false;
    var up1=false;
    var down1=false;
    var flag=false;
    var aa=false;
    
    init();
    function k_down(e)
    {
        down[e.keyCode]=true;
    
        clearInterval(timer);
        //sp=10;
    
        if(down[37])
        {   
            if(sp>2)
            {
                sp++;
            }
            dy=0;
            dx=-3;
            left=true;
            flag=false;
            //down=[];
        }
    
        else if(down[38])
        {
            if(sp>2)
            {
                sp++;
            }
            dx=0;
            dy=-4;
    
            up1=true;
            flag=false;
            //down=[];
        }
    
        else if(down[39])
        {
            if(sp>2)
            {
                sp++;
            }
            dy=0;
            dx=3;
    
            right=true;
            flag=false;
            //down=[];
        }
    
        else if(down[40])
        {
            if(sp>2)
            {
                sp++;
            }
            dx=0;
            dy=4;
    
            down1=true;
            flag=false;
            //down=[];
        }
    
    
        if(down[65])
        {   
    
            dy1=0;
            dx1=-3;
    
        }
        else if(down[87])
        {
            dx1=0;
            dy1=-4;
    
        }
        else if(down[68])
        {
            dy1=0;
            dx1=3;
        }
        else if(down[83])
        {
            dx1=0;
            dy1=4;
        }
        //console.log("speed++>"+sp);
        timer=setInterval(draw,sp);
        down[e.keyCode]=false;
    }
    
    
    function k_up(e)
    {
        up=e.keyCode;
        //alert(sp);
        if(sp<10)
        {
            sp=10;
            clearInterval(timer);
            timer=setInterval(draw,10);
        }
        //console.log("upp->>"+down);
        if(left==true && up1==true)
        {
            //console.log("1");
            sp=2;
            clearInterval(timer);
            timer=setInterval(draw,sp);
            dx=-3;
            dy=-4;
            flag=true;
        }
        else if(left==true && down1==true)
        {
            //console.log("2");
            sp=2;
            clearInterval(timer);
            timer=setInterval(draw,sp);
    
            dx=-3;
            dy=4;
            flag=true;
        }
        else if(right==true && up1==true)
        {
            //console.log("3");
            sp=2;
            clearInterval(timer);
            timer=setInterval(draw,sp);
    
            dx=3;
            dy=-4;
            flag=true;
        }
        else if(right==true && down1==true)
        {
            //console.log("4");
            sp=2;
            clearInterval(timer);
            timer=setInterval(draw,sp);
    
            dx=3;
            dy=4;
            flag=true;
        }
        if(left==true)
        {
            if(flag==false){
            dy=0;
            dx=-3;
            }
        }
        else if(up1==true)
        {
            if(flag==false){
            dx=0;
            dy=-4;
            }
        }
        else if(right==true)
        {
            if(flag==false){
            dy=0;
            dx=3;
            }
        }
        else if(down1==true)
        {
            if(flag==false){
            dx=0;
            dy=4;
            }
        }
    
        if (up==37)
        {
            left=false;
        }
        else if (up==38)
        {
            up1=false;
        }
        else if (up==39)
        {
            right=false;
        }
        else if (up==40)
        {
            down1=false;
        }
    
    }
    
    function circle(x,y,r) {
      ctx.beginPath();
      ctx.arc(x, y, r, 0, Math.PI*2, true);
      ctx.closePath();
      ctx.fill();
    }
    
    function rect(x,y,w,h) {
      ctx.beginPath();
      ctx.rect(x,y,w,h);
      ctx.closePath();
      ctx.fill();
    }
    
    function clear() {
      ctx.clearRect(0, 0, 307, 211);
    }
    
    function init() {
      //ctx = $("#canvas").getContext("2d");
      ctx = document.getElementById('canvas').getContext("2d");
      //WIDTH = $("#canvas").width()
      //HEIGHT = $("#canvas").height()
      //canvas.addEventListener("click", getPosition, false);
      return setInterval(draw, 10);
    
    }
    /*
    function getPosition(event)
    {
    //  var canvas = document.getElementById("canvas");
     // var x = event.x;
      //var y = event.y;
     // x -= canvas.offsetLeft;
    //  y -= canvas.offsetTop;
    
      //alert("x: " + x + "  y: " + y);
    } 
    */
    function draw() {
      clear();
      circle(x, y, 10);
      circle(x1, y1, 10);
    
    
    
    
    
      if (x + dx  > WIDTH || x + dx < 0)
        dx = -dx;
      if (y + dy > HEIGHT || y + dy < 0)
        dy = -dy;
      x += dx;
      y += dy;
      console.log("x->"+x)
        if (x==10){
        dx = -dx;
      x += dx;
      y += dy;
      }
      if (y==10){
        dy = -dy;
      x += dx;
      y += dy;
      }
    
      if (x1 + dx1 > WIDTH || x1 + dx1 < 0)
        dx1 = -dx1;
      if (y1 + dy1 > HEIGHT || y1 + dy1 < 0)
        dy1 = -dy1;
      x1 += dx1;
      y1 += dy1;
      console.log("x1->"+x1)
      if (x1==10){
        dx1 = -dx1;
      x1 += dx1;
      y1 += dy1;
      }
      if (y1==10){
        dy1 = -dy1;
      x1 += dx1;
      y1 += dy1;
      }
    }
    
    
    
    
    </script>
    </body>
    </html>