fromJSON 方法是 RectangleTriggerRegion 类的静态方法,用于将一个符合约定好的 JSON 格式的对象转换为 RectangleTriggerRegion 对象。
RectangleTriggerRegion.fromJSON(json)
json: 表示一个符合约定好的 JSON 格式的对象,必须包含以下属性:
type: 必填。表示触发器的类型,必须为字符串 "rectangle"。x: 必填。表示触发器区域左上角点的 x 坐标,必须为数字类型。y: 必填。表示触发器区域左上角点的 y 坐标,必须为数字类型。width: 必填。表示触发器区域的宽度,必须为数字类型,并大于 0。height: 必填。表示触发器区域的高度,必须为数字类型,并大于 0。RectangleTriggerRegion 对象。
// JSON 数据
const json = {
type: 'rectangle',
x: 10,
y: 20,
width: 100,
height: 80
};
// 转换为 RectangleTriggerRegion 对象
const region = RectangleTriggerRegion.fromJSON(json);
console.log(region.x); // 10
console.log(region.y); // 20
console.log(region.width); // 100
console.log(region.height); // 80
console.log(region.type); // 'rectangle'
如果传入的 JSON 对象不符合规范,则会抛出异常。具体来说,如果以下条件之一被满足,则会抛出异常:
json 参数,或传入的 json 参数不是一个对象。json.type 不等于字符串 "rectangle"。json.x 或 json.y 或 json.width 或 json.height 不是数字,或小于等于 0。RectangleTriggerRegion 对象是完整的触发器区域,并已经初始化完毕,可以直接被使用。