1

如何使用 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>
4

2 回答 2

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>
于 2013-07-19T15:21:23.437 回答
0

two ball are move diff. side on key board .

  1. first ball to move to keyboard to up, down , right, left key
  2. second ball move to A(left side), W(up side) ,D(right side) and S(down side).

just copy and past in your screen.

<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>
于 2015-10-16T08:00:28.453 回答