如何防止图像超出屏幕边界?

时间:2020-08-04 17:15:45

标签: javascript 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 (keys[39] || keys[68]) {pos.left += 10}
if (keys[38] || keys[90]) {pos.top -= 1}
if (keys[40] || keys[83]) {pos.top += 1}
rect.style.left = pos.left + "px"; rect.style.top = pos.top + "%"}
let sens = setInterval(loop, 1000 / 40)

背景代码

width: 100%;
background-image: url(Photo/bg.jpg);
background-repeat: no-repeat;
background-attachment: fixed;
background-size: cover;
overflow: hidden; }

2 个答案:

答案 0 :(得分:0)

尝试使用position:relative;用于容器元素

答案 1 :(得分:0)

当顶部/左侧位置超出范围时,您需要对其进行校正,将其固定到极限边界(owidth / {{1}是容器尺寸,oheight / {{1 }}是元素尺寸。

iwidth

应用于示例代码(为了简化计算,我将iheight的增量更改为 if (pos.left<0) pos.left=0; if (pos.top<0) pos.top=0; if (pos.left+iwidth>=owidth) pos.left=owidth-iwidth; if (pos.top+iheight>=oheight) pos.top=oheight-iheight; 的增量)。否则,您需要使用容器高度将百分比转换为以像素为单位的顶部位置。

%
px
(function(){

let display = document.getElementById("body");
let rect = document.getElementById("icon-p1");
let pos = {top: 85, left: 100}
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 (keys[39] || keys[68]) {pos.left += 10}
 if (keys[38] || keys[90]) {pos.top -= 10}
 if (keys[40] || keys[83]) {pos.top += 10}
 var owidth=display.offsetWidth;
 var oheight=display.offsetHeight;
 var iwidth=rect.offsetWidth;
 var iheight=rect.offsetHeight;
 if (pos.left<0) pos.left=0;
 if (pos.top<0) pos.top=0;
 if (pos.left+iwidth>=owidth) pos.left=owidth-iwidth;
 if (pos.top+iheight>=oheight) pos.top=oheight-iheight;
 rect.setAttribute("data",owidth+":"+oheight);
 rect.style.left = pos.left + "px"; rect.style.top = pos.top + "px"
}

let sens = setInterval(loop, 1000 / 40)

})();