简体   繁体   English

Javascript onkeydown功能不起作用

[英]Javascript onkeydown function doesn't work

Why is it impossible to move the canvas circle? 为什么不可能移动画布圈? just provide me with tips what's wrong with listener. 只是向我提供提示收听者有什么问题。 i understand that i've done some bad mistakes but nevermind them,i just can't understand principe behind changing position of object. 我知道我犯了一些严重的错误,但没想过它们,我只是不明白更改对象位置背后的原理。

<!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>

There is no need to add "px"(unit) to the width and height of the canvas 无需在画布的宽度和高度上添加“ px”(单位)

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

You forgot to redraw the canvas when you press the key 您忘记按键时重新绘制画布

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();

For more infomation about KeyboardEvent, go to MDN KeyboardEvent 有关KeyboardEvent的更多信息,请转到MDN KeyboardEvent。

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

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