KonvaJS变换后如何重置矩形的x、y、宽、高,解决翻转后参数异常问题
KonvaJS 矩形调整大小后重置属性的正确方案
你遇到的异常是因为向左/向上拖拽变换控制点导致矩形翻转时,Konva 会将 scaleX/scaleY 赋值为负值,直接用缩放值乘原始宽高会得到负的尺寸,且此时原有的 x/y 坐标已经不再对应矩形左上角的位置。
你要的翻转标识可以直接通过缩放值的正负判断:scaleX < 0 代表水平翻转,scaleY < 0 代表垂直翻转,基于这个逻辑调整坐标和尺寸即可,正确实现代码如下:
myRectangle.on('transformend', function() { // 获取当前所有变换参数 const scaleX = this.scaleX(); const scaleY = this.scaleY(); let width = this.width() * scaleX; let height = this.height() * scaleY; let x = this.x(); let y = this.y(); // 处理水平翻转场景 if (scaleX < 0) { x += width; // 此时width为负值,等价于x减去宽度绝对值,修正左上角x坐标 width = Math.abs(width); } // 处理垂直翻转场景 if (scaleY < 0) { y += height; // 同理修正左上角y坐标 height = Math.abs(height); } // 赋值修正后的属性,重置缩放为1 this.x(Math.round(x)); this.y(Math.round(y)); this.width(Math.round(width)); this.height(Math.round(height)); this.scaleX(1); this.scaleY(1); });
以上逻辑执行后,矩形的x/y始终对应左上角坐标,width/height始终为正值,可直接提取使用。
内容的提问来源于stack exchange,提问作者user2225232
相关产品推荐
相关产品推荐

