fabricjs getBoundingRect() 返回没放大的宽高、左上角的坐标 作者:马育民 • 2024-10-20 10:18 • 阅读:10000 # 说明 ``` getBoundingRect() ``` 返回值如下: ``` { left: 0.37057876262304035, top: 3.6, width: 138.6423984845793, // 宽度 * scaleX + 边框宽度 height: 84.02261048383794 // 高度 * scaleX + 边框宽度 } ``` ### 直线倾斜时的 宽度、高度 如果添加的是 **水平的直线**,当倾斜后,该方法返回的宽度如下图所示: [![](/upload/0/0/1IX8dnmxUEzf.jpg)](/upload/0/0/1IX8dnmxUEzf.jpg) 而不是 直线 **本身的宽度** ### 注意:高分辨率屏幕 如果是普通屏幕,各个值不需要额外处理 如果是 **高分辨率屏幕**,一般 **屏幕会放大**,如下图: [![](/upload/0/0/1IX8OYh5ktYy.jpg)](/upload/0/0/1IX8OYh5ktYy.jpg) 但返回的各个值是 **没放大** 的 所以,如果屏幕放大了,那么 **各个值需要 乘上** `1.25` ### 获取放大比例 通过下面方式可以获取放大比例: ``` window.devicePixelRatio ``` ### 验证 ``` console.log("属性(高分辨率屏幕放大后的值):", element.left, element.top, element.width, element.height, element.angle, element.scaleX, element.scaleY ) const br = element.getBoundingRect() console.log("真实值:",br) ``` ``` // 下面两个宽度几乎相等(有小数,可能有误差) console.log( "放大后的值:", element.width * element.scaleX + element.strokeWidth) console.log( "getBoundingRect中的宽度 * 1.25",element.getBoundingRect().width * window.devicePixelRatio ) ``` ``` // 下面两个left几乎相等(有小数,可能有误差) console.log( "放大后的值:", element.left ) console.log( "getBoundingRect中的left * 1.25",element.getBoundingRect().left * window.devicePixelRatio ) ``` 原文出处:http://malaoshi.top/show_1IX8digVM1cT.html