如何在JavaScript中移动<img/>元素?

时间:2016-02-05 05:46:50

标签: javascript html

有人可以帮我看看我的代码吗? 我试图在画布中移动图像,但它不会移动。我的代码可能有误。有谁可以帮助我吗?谢谢!

<script>
var canvas;
var canvasContext;

var framesPerSecond = 30;

var posX = 10;
var posY = 10;

window.onload = function(){
    canvas = document.getElementById("playGround");
    canvasContext = canvas.getContext("2d");
    setInterval(drawEverything(), 1000/framesPerSecond);
    canvas.addEventListener("keydown", moveImg);
}

function drawEverything(){
    colorRect(0,0,canvas.width,canvas.height,"black");
    drawImage("mario",posX,posY);
}

function drawImage(id, x, y){
    var img = document.getElementById(id);
    canvasContext.drawImage(img,x,y,30,30);
}

function colorRect(x, y, width, height, color){
    canvasContext.fillStyle = color;
    canvasContext.rect(x,y,width,height);
    canvasContext.stroke();
}

function moveImg(evt){
    switch(evt.keyCode) {
        // Left arrow key pressed
        case 37:
            posX-=5;
            break;
        // Up Arrow Pressed
        case 38:
            posY-=5;
            break;
        // Right Arrow Pressed
        case 39:
            posX+=5;
            break;
        // Down Arrow Pressed
        case 40:
            posY+=5;
            break;
    }};
 </script>

我在网上查看了答案,但我似乎找不到任何东西。也许我有语法问题?

1 个答案:

答案 0 :(得分:1)

您有两个问题,如下所示。检查工作演示 - Fiddle(首先点击右下方的任意位置以设置焦点):

  1. Canvas没有焦点,因此您必须将canvas.addEventListener("keydown", moveImg);更改为document.addEventListener("keydown", moveImg);

  2. moveImg功能中,您忘记根据按下的键更新图像位置。在switch语句后添加drawImage("mario",posX,posY);