javascript - 如何防止图像隐藏在边框之外
问题描述
所以我目前正在构建一个视频游戏,其中我的图像随着键盘控制器移动。问题是这个图标超出了屏幕边框。有人知道如何处理这个(请只用js或css)吗?谢谢
图标随控制器移动:
let display = document.getElementById("body").style.width
let rect = document.getElementById("icon-p1")
let pos = {top: 85, left: 600}
const keys = {}
window.addEventListener("keydown", function(e) {keys[e.keyCode] = true})
window.addEventListener("keyup", function(e) {keys[e.keyCode] = false})
const loop = function() {
if (keys[37] || keys[81]) {pos.left -= 10; if (display < 100) {pos.left -= 0}}
if (keys[39] || keys[68]) {pos.left += 10; if (display < 100) {pos.left += 0}}
if (keys[38] || keys[90]) {pos.top -= 1; if (display < 100) {pos.top -= 0}}
if (keys[40] || keys[83]) {pos.top += 1; if (display < 100) {pos.top += 0}}
rect.style.left = pos.left + "px"; rect.style.top = pos.top + "%"}
let sens = setInterval(loop, 1000 / 40)
背景图像的CSS:
body {
background-image: url(Photo/bg.jpg);
background-repeat: no-repeat;
background-attachment: fixed;
background-size: cover;
overflow: hidden; }
解决方案
检查框是否距离边界足够远:
// just storing the movement increment in a variable to make code softer
let moveInc = 10;
// this is the width of the boundary. If the boundary/container has a width of 600px, this will be 600.
let containerWidth = document.getElementById("yourContainerID/screenID").style.width;
// this is the height of the boundary. If the boundary/container has a height of 800px, this will be 800.
let containerHeight = document.getElementById("yourContainerID/screenID").style.height;
// here is the function from your code
const loop = function() {
// you will be better off formatting your code to match mine (aka no one-liner if statements)
if (keys[37] || keys[81]) {
if (pos.left > 0 + moveInc)// 0 is the left boundary, and the moveInc will act as a buffer to stop any overlap with the left boundary
pos.left -= moveInc;
}
if (keys[39] || keys[68]) {
if (pos.left + rect.style.width < containerWidth - moveInc)// containerWidth is the right boundary, again moveInc is a buffer
pos.left += moveInc;
}
...
}
然后,您可以对顶部和底部使用相同的主体。
顶部将与左侧相当
底部将与右侧相当