javascript - 旧浏览器中 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了。
你能建议:
- 在早期浏览器中工作的 DOMRect 的替代方案
- 或完全替代 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,以便其他属性保持同步。
推荐阅读
- javascript - 如何在 React 中以键值对的形式显示嵌套的 json 数据?
- protocol-buffers - 如何检查 protoc-gen-go 和 protoc-gen-validate 的版本?
- input - ffmpeg 第一次运行命令时总是给我输入/输出错误
- angular - 使用 HttpClient 模块在 Angular 中出现错误
- mysql - 使用 quarkus 的反应式 MySQL 配置
- bash - 解决了带有变量的 BASH 选项卡完成中的错误
- python - Python将请求响应中的文件内容写入相应文件
- swiftui - SwiftUI 阻止 Divider 在 HStack 中垂直扩展
- r - 为什么“c”在这里等于 1000?
- r - 如何查看/更改 RStudio 使用的 R 安装?