首页 > 解决方案 > 旧浏览器中 DOMRect 的替代方案

问题描述

我正在教一个人 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 未定义”在以下行:

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,同时保留我们应用程序的逻辑

标签: javascriptrect

解决方案


您可以在代码中添加一个 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,以便其他属性保持同步。


推荐阅读