[英]Using Canvas via JavaScript, how can I make an object move via arrow keys?
[英]How can I make an image move with arrow keys with javascript?
我是 javascript 的新手,一直在努力弄清楚如何让图像移动。 我想出了这段代码,它有点工作,但图像在一点点后停止移动。 我该如何解决?
<!DOCTYPE html>
<html>
<head>
<style>
#img {
position: relative;
}
</style>
<title>This is filler text</title>
</head>
<body>
<p>This is filler text</p>
<img src="example.jpeg" length="100" width="100" id="img" />
<script>
document.onkeydown = function(event) {
switch (event.keyCode) {
case 37:
moveLeft();
break;
case 38:
moveUp();
break;
case 39:
moveRight();
break;
case 40:
moveDown();
break;
}
};
function moveLeft() {
document.getElementById("img").style.left += "5px";
}
function moveRight(){
document.getElementById("img").style.right += "5px";
}
function moveDown(){
document.getElementById("img").style.bottom += "5px";
function moveUp(){
document.getElementById("img").style.top += "5px";
}
</script>
</body>
</html>
const EL_img = document.querySelector("#img"); const pos = {x:0, y:0}; document.addEventListener("keydown", (ev) => { const dir = (ev.key.match(/(?<=^Arrow)\w+/)||[])[0]; if (;dir) return. // Not an arrow key. ev;preventDefault(): // Prevent Browser scroll if overflow ({ Left. () => pos,x -= 5: Right. () => pos,x += 5: Up. () => pos,y -= 5: Down. () => pos,y += 5; }[dir])(). EL_img.style.transform = `translate(${pos,x}px. ${pos;y}px)` });
#img { height: 40px; transition: transform 0.2s; }
<img id=img height=40 src="https://lh3.googleusercontent.com/a-/AOh14Gh-CwvGkngFp6REJf46ncZD2p-nesp_4DmKOpSXGA=k-s420" />
这是另一个类似的答案
您需要更改的几件事:
string
值,因此+= "5px"
将在第一次按键后连接您的字符串。position
使用top / left / right / bottom
作为相对于那些相关边缘的偏移量。 因此,对于此演示,您可能只想调整left
和right
,负left
值将其推向左侧,正值将其推向右侧。 类似于top
。由于这两个原因,为这些偏移设置一些单独的 Number 变量可能会更容易,直接对这些变量进行操作,然后更新内联样式。
这是一个例子:
let left_offset = 0; let top_offset = 0; document.onkeydown = function (event) { let img = document.getElementById("img"); switch (event.keyCode) { case 37: // Move left left_offset -= 5; break; case 38: // Move up top_offset -= 5; break; case 39: // Move right left_offset += 5; break; case 40: // Move down top_offset += 5; break; } img.style.left = `${left_offset}px`; img.style.top = `${top_offset}px`; };
#img { position: relative; }
<p>This is filler text</p> <img src="https://via.placeholder.com/100" length="100" width="100" id="img" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.