<style>
#canvas {
position: absolute;
left: 50%;
top: 50%;
/* width: 500px;
height: 500px; */
transform: translate(-50%, -50%);
border: 2px black solid;
}
</style>
<body>
<canvas width="500px" height="500px" id="canvas">您的浏览器版本过低</canvas>
<script>
var canvas = document.getElementById('canvas');
var c = canvas.getContext('2d');
var w = 500;
var h = 500;
var x = 100;
var y = 100;
var r = 20;
// 水平速度
xSpeed = 5;
// 垂直速度
ySpeed = 5;
setInterval(function () {
c.clearRect(0, 0, w, h);
move();
// 更新圆的位置
drawCircle(x, y, r);
}, 10)
function move () {
document.onkeydown = function (event) {
if (event.keyCode === 38) {
console.log("上键被按下了");
//以下三种都可以实现上移键盘事件
y = y - ySpeed;
// setInterval(function () { y = y - ySpeed; }, 10)
// y--
} else if (event.keyCode === 40) {
console.log("下键被按下了");
//以下三种都可以实现下移键盘事件
// setInterval(function () { y = y + ySpeed; }, 10)
y = y + ySpeed;
// y++;
} else if (event.keyCode === 37) {
console.log("左键被按下了");
//以下三种都可以实现左移键盘事件
// setInterval(function () { x = x - xSpeed; }, 10)
// xSpeed = xSpeed;
x = x - xSpeed;
// x--;
} else if (event.keyCode === 39) {
console.log("右键被按下了");
// setInterval(function () { x = x + xSpeed; }, 10)
// return ;
// exit(0);
x = x + xSpeed;
// x++;
}
};
}
//画圆
function drawCircle (x, y, r) {
c.beginPath();
c.arc(x, y, r, 0, Math.PI * 2);
c.fillStyle = 'gold';
c.fill();
}
</script>
</body>