【html】控制飛機圖片移動
阿新 • • 發佈:2020-12-28
技術標籤:jshtmljavascript
按鍵控制
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#box{
width: 1000px;
height: 700px;
border: 1px solid #ff0000;
position : relative;
}
</style>
</head>
<body>
<div id="box" class="box" tabindex="1">
</div>
<script>
var hero = {
img:new Image(),
x:100,
y:200,
w:90,
h:60,
speed:10,
draw:function () {
let that = this;
that.img.src='hero.png';
that.img.onload=function () {
this.style.position='absolute';
this.style.left=`${that.x}px`;
this.style.top=`${that.y}px`;
this.width = that.w;
this .height = that.h;
document.getElementById('box').appendChild(this);
}
},
moveTo:function (e) {
let code = e.keyCode;
let x = 0;
let y = 0;
switch (code) {
case 37:
//左
x -= this.speed;
break;
case 38:
//上
y -= this.speed;
break;
case 39:
//右
x += this.speed;
break;
case 40:
//下
y += this.speed;
break;
}
this.x += x;
this.y += y;
if (this.x > 910){
this.x = 910;
}else if(this.y > 640){
this.y=640;
}else if(this.x < 0){
this.x = 0;
}else if(this.y < 0){
this.y = 0;
}
this.draw();
}
}
hero.draw();
document.getElementById('box').addEventListener('keydown',function (e) {
hero.moveTo(e);
})
</script>
</body>
</html>
滑鼠控制:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#box{
width: 1000px;
height: 700px;
border: 1px solid #ff0000;
position: relative;
}
</style>
</head>
<body>
<div id="box">
</div>
<script>
var hero = {
img:new Image(),
x:100,
y:200,
w:90,
h:60,
speed:10,
draw:function () {
let that = this;
that.img.src='hero.png';
that.img.onload=function () {
this.style.position='absolute';
this.style.left=`${that.x}px`;
this.style.top=`${that.y}px`;
this.width = that.w;
this.height = that.h;
document.getElementById('box').appendChild(this);
}
},
moveTo:function (x,y) {
this.x = x;
this.y = y;
this.draw();
}
}
hero.draw();
document.getElementById('box').addEventListener('mousemove',function (e) {
let x = e.x;
let y = e.y;
hero.moveTo(x,y);
})
</script>
</body>
</html>