JavaScript实现控制小球移动
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>Events: Task 2</title>
<style>
p {
color: purple;
margin: 0.5em 0;
}
* {
box-sizing: border-box;
}
canvas {
border: 1px solid black;
}
</style>
<link rel="stylesheet" href="../styles.css" />
</head>
<body>
<section class="preview">
</section>
<canvas width="480" height="320" tabindex="0">
</canvas>
</body>
<script>
let canvas = document.querySelector('canvas');
let ctx = canvas.getContext('2d');
function drawCircle(x, y, size) {
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.fillStyle = 'black';
ctx.arc(x, y, size, 0, 2 * Math.PI);
ctx.fill();
}
let x = 50;
let y = 50;
const size = 30;
drawCircle(x, y, size);
// Add your code here
// window.addEventListener('keyup', function(e) {
window.addEventListener('keydown', function(e) {
if(e.which === 65 && x >= 35) {
x -= 5
}
if(e.which === 68 && x <= 445) {
x += 5
}
if(e.which === 87 && y >= 35) {
y -= 5
}
if(e.which === 83 && y <= 285) {
y += 5
}
drawCircle(x, y, size)
console.log(e.which)
})
</script>
</html>
阅读量: 635
发布于:
修改于:
发布于:
修改于: