旧浏览器中 DOMRect 的替代品

An alternative to DOMRect in older browsers

我正在教一个人 JS,我们正在编写游戏。为了检测碰撞,我们使用 DOMRect 对象。这两个对象中的每一个都像这样给我们它的矩形:

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_loop每一帧我们这样称呼它:

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

在我的机器上代码运行良好。在我学生的机器上它不起作用。浏览器显示:'DOMRect is undefined' 在具有:

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

我的学生有一台装有 Win XP 的非常旧的 PC。他的 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;
};

你当然不应该有修改任何属性的代码。如果是这种情况,您应该为这些属性创建 getter 和 setter,以便其他属性保持同步。