旧浏览器中DOMRect的替代方案



我正在教一个家伙JS,我们正在编写一个游戏。为了检测碰撞,我们使用DOMRefect对象。这两个对象中的每一个都给了我们一个矩形,如下所示:

get_rect(){
return new DOMRect (this.x, this.y, this.width, this.height);
}

在主文件中,我们有一个检查冲突的功能:

function rects_intersect(rect_a, rect_b) {
return (rect_a.left <= rect_b.right && 
rect_b.left <= rect_a.right &&
rect_a.top <= rect_b.bottom &&
rect_b.top <= rect_a.bottom);
}

在game_oop中,我们这样称呼每一帧:

if(rects_intersect(player.get_rect(), enemy.get_rect()) == true){
alert('collision')
}

在我的机器上,代码运行良好。在我学生的机器上,它不工作。浏览器在具有的行处显示:"DOMRect未定义">

return new DOMRect(this.x, this.y, this.img.width, this.img.height);

我的学生有一台很旧的电脑,上面有WinXP。他的Chrome是49.0.2623.112。他说他不能再更新XP了。

你能建议一下吗:

  1. 在早期浏览器中工作的DOMRect的替代方案
  2. 或者完全替代DOMRect,同时保留我们应用程序的逻辑

您可以在代码中添加polyfill,只有在尚未定义DOMRect的情况下才会生效:

var DOMRect = DOMRect || function (x, y, width, height) { 
this.x = this.left = x;
this.y = this.top = y;
this.width = width;
this.height = height;
this.bottom = y + height;
this.right = x + width;
};

当然,您不应该有修改任何属性的代码。如果是这样的话,你应该制作getters&这些属性的setter,因此其他属性保持同步。

最新更新