简体   繁体   English

如何使用html5中的键盘箭头键在画布上移动图像

[英]how to move an image on canvas using keyboard arrow key in html5

I m Drawing the image on canvas with this code and it successfully draw the image on canvas now i want to move the image on canvas for that i write the code i check that if the right key of my keyboard is pressed i will increment the x coordinate of an image if left key is pressed i will decrement the x coordinate but image is not moving on the canvas 我用这个代码在画布上绘制图像并且它成功地在画布上绘制图像现在我想在画布上移动图像我编写代码我检查如果键盘的右键被按下我会增加x如果按下左键,图像的坐标将减小x坐标但图像不在画布上移动

player = new Image();
player.src = "game_character.png";
context.drawImage(player,player.x * wallDim + wallDim ,player.y * wallDim + wallDim ,50,50);

how to move an image on canvas 如何在画布上移动图像

 var handleInput = function(event, keyState) {
        switch(event.which) {
              case 37: { // Left Arrow
                    keyDown.arrowLeft = keyState;
                    break;
              }
              case 38: { // Up Arrow
                    keyDown.arrowUp = keyState;
                    break;
              }
              case 39: { // Right Arrow
                    keyDown.arrowRight = keyState;
                    break;
              }
              case 40: { // Down Arrow
                    keyDown.arrowDown = keyState;
                    break;
              }
        }
  }

  /**
  * physics
  *
  * This function contains the basic logic for the maze.
  */
  var physics = function() {
       console.log("physics ");
       console.log("first condition "+keyDown.arrowRight +player.x+1);
        if(keyDown.arrowLeft && player.x-1 >= 0 && map[player.y][player.x-1] != 1) {
              player.x--;
              redraw = true;
        }

        if(keyDown.arrowUp && player.y-1 >= 0 && map[player.y-1][player.x] != 1) {
              player.y--;
              redraw = true;
        }

        if(keyDown.arrowRight && player.x+1 < map[0].length && map[player.y][player.x+1] != 1) {
              console.log("arrow right");
              player.x++;
              redraw = true;
        }

        if(keyDown.arrowDown && player.y+1 < map.length && map[player.y+1][player.x] != 1) {
              player.y++;
              redraw = true;
        }
        if(keyDown.arrowRight && player.x+1 >= map[0].length)
        {
            player.x++;
            document.getElementById("canvas_div").style.display="none";
            document.getElementById("end_screen_div").style.display="block";
            //alert("completed");
        }
  }

  /**
  * draw
  *
  * This function simply draws the current state of the game.
  */
  var draw = function() {

        // Don't redraw if nothing has changed
        if(!redraw)
              return;

        context.clearRect(0, 0, cols, rows);
        context.beginPath();

        // Draw the maze
        for(var a = 0; a < rows; a++) {
              for(var b = 0; b < cols; b++) {
                    switch(map[a][b]) {
                          case C.EMPTY: context.fillStyle = colors.empty; break;
                          case C.WALL: context.fillStyle = colors.wall; break;
                    }

                        context.fillRect(b * wallDim, a * wallDim, wallDim, wallDim); // x, y, width, height
              }
        }

        // Draw the player
     /* context.fillStyle = colors.player;
        context.arc(
              player.x * wallDim + wallDim / 2, // x position
              player.y * wallDim + wallDim / 2, // y position
              wallDim / 2, // Radius
              0, // Starting angle
              Math.PI * 2, // Ending angle
              true // antiClockwise
        );*/


    player = new Image();
    player.src = "game_character.png";

    context.drawImage(player,player.x * wallDim + wallDim ,player.y * wallDim + wallDim ,50,50);

    var firstplayer=new Image();
    firstplayer.src="top_character01.png";

    context.drawImage(firstplayer,680,0,60,60);

    var secondplayer= new Image();
    secondplayer.src="top_character02.png";

    context.drawImage(secondplayer,750,0,60,60);

    context.fill();
    context.closePath();

        redraw = false;
  }

In your draw method, you reinitialize the player each time : 在您的绘制方法中,您每次都重新初始化播放器:

player = new Image();
player.src = "game_character.png";

So you erase the player.x modified by your event handler. 所以你擦除了由事件处理程序修改的player.x.

You should initialize the player only once, outside the draw function. 您应该只在绘图功能之外初始化播放器一次。 You can move the initialization like this : 您可以像这样移动初始化:

var player = new Image();
player.src = "game_character.png";
var draw = function() {

There is absolutely no need to call player.src = "game_character.png"; 绝对没有必要调用player.src = "game_character.png"; inside the draw function. 在绘制功能中。

As a general rule, when dealing with animation, try to remove all what you can from the draw function, which should be as fast as possible. 作为一般规则,在处理动画时,尝试从draw函数中删除所有内容,尽可能快。

You will need to redraw the canvas each time. 您每次都需要重绘画布。 Something like this: 像这样的东西:

function init()
{
    canvas = document.getElementById("canvas");
    context = canvas.getContext("2d");

    x = canvas.width / 2; //align to centre of the screen
    y = canvas.height / 2; //same as above

    speed = 5; //speed for the player to move at

    width = 50; //width of the player
    height = 50; //height of the player

    playerimage = new Image();
    playerimage.src = "path/to/image/for/player"; //path to the image to use for the player

    canvas.addEventListener("keypress", update);
}

function update(event)
{
    if (event.keyCode == 38)
    {
        y -= speed; //going up
    }
    if (event.keyCode == 40)
    {
        y += speed; //going down
    }
    if (event.keyCode == 37)
    {
        x -= speed; //going left
    }
    if (event.keyCode == 39)
    {
        x += speed; //going right
    }
    render();
}

function render()
{
    context.clearRect(0, 0, canvas.width, canvas.height);
    context.drawImage(playerimage, x, y, width, height);
}

I haven't tested it, so I don't know whether it works and there may be some mistakes here and there. 我没有测试过,所以我不知道它是否有效,并且可能会出现一些错误。 It should work though! 它应该工作! If nothing else, it will (hopefully) give you an idea of one way in which you can go about doing it... 如果没有别的,它(希望)会让你知道一种方法,你可以去做...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM