Javascript onkeydown功能不起作用

时间:2017-09-17 23:23:41

标签: javascript html5-canvas

为什么移动画布圈不可能?只是告诉我听众的错误。我知道我做了一些不好的错误,但从未明白过,我只能理解改变对象位置背后的原则。

<!DOCTYPE html>
<html>
<head>
    <title>epicGame</title>
</head>
<body>
<canvas id="myCanvas" width="600px" height="600px" style="border:1px solid black"></canvas>
<script type="text/javascript">
var c = document.getElementById("myCanvas");
var ctx = c.getContext('2d');
function drawCircle(){
ctx.beginPath();
ctx.fillStyle="red";
ctx.fill();
}
var velX=50;
var Player1={
    x:150,
    y:70,
    velX:20,
    velY:5,
    hp:20,
    startAngle:40,
};
function drawPlayer1(){
    ctx.beginPath();
    ctx.arc(Player1.x,Player1.y,Player1.startAngle,0,2*Math.PI);
    ctx.fillStyle="red";
    ctx.fill();
}
function move(key){
    if(key.keyCode=="32"){
        updatePosition();
    }
}
function updatePosition(){
    Player1.x+=Player1.velX;
        ctx.arc(Player1.x,Player1.y,Player1.startAngle,0,2*Math.PI);
}
drawPlayer1();

window.addEventListener("keydown",move,false);
</script>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

无需在画布的宽度和高度上添加“px”(单位)

<canvas id="myCanvas" width="600" height="600" style="border: 1px solid black;"></canvas>

按键

时忘记重绘画布
var c = document.getElementById('myCanvas');
var ctx = c.getContext('2d');

// since the circle are always red, set ctx.fillStyle to red
ctx.fillStyle = 'red';

var Player1={
    x: 150,
    y: 70,
    velX: 20,
    velY: 5,
    hp: 20,
    startAngle: 40,
};

function drawPlayer1(){

    ctx.beginPath();
    ctx.arc(Player1.x, Player1.y, Player1.startAngle, 0, 2 * Math.PI);
    ctx.fill();
}

function move(event){

    // the event.keyCode is Deprecated, use event.code or event.key
    if(event.code === 'Space' || event.key === ' '){
        updatePosition();
    }
}

function updatePosition(){

    // update Player1's property
    Player1.x += Player1.velX;

    // erase the canvas
    ctx.clearRect(0, 0, c.width, c.height);

    // redraw Player1
    drawPlayer1();
}

// bind event
window.addEventListener('keydown', move, false);

// initialize
drawPlayer1();

有关KeyboardEvent的更多信息,请转到MDN KeyboardEvent