Kinetic JS – 试图调整图像大小的问题

我刚开始使用Kinetic JS。

如果你看这个链接: 例子

一些代码在这里:

function update(group, activeHandle) { var topLeft = group.get(".topLeft")[0], topRight = group.get(".topRight")[0], bottomRight = group.get(".bottomRight")[0], bottomLeft = group.get(".bottomLeft")[0], image = group.get(".image")[0], activeHandleName = activeHandle.getName(), newWidth, newHeight, imageX, imageY; // Update the positions of handles during drag. // This needs to happen so the dimension calculation can use the // handle positions to determine the new width/height. switch (activeHandleName) { case "topLeft": topRight.setY(activeHandle.getY()); bottomLeft.setX(activeHandle.getX()); break; case "topRight": topLeft.setY(activeHandle.getY()); bottomRight.setX(activeHandle.getX()); break; case "bottomRight": bottomLeft.setY(activeHandle.getY()); topRight.setX(activeHandle.getX()); break; case "bottomLeft": bottomRight.setY(activeHandle.getY()); topLeft.setX(activeHandle.getX()); break; } 

其余代码位于jsdFiddle链接中。 我可能错过了一些明显的东西!

你会看到2个被锚点包围的图像。 resize或拖动图像时,图像不得越过黑色矩形(即边界)。 拖动工作 – 只要图像之前没有resize。

resize的图像仍然跨越边界。 然后拖放的调整后的图像往往会创建自己的不可见边界(如果调整图像大小的人不使用右下角的锚点来resize)。

谁能看到我做错了什么?

非常感谢您的帮助!

您遇到的问题是,当您通过拉动锚点调整图像大小时,您将设置图像的位置,如下所示:

 if(activeHandleName === "topRight" || activeHandleName === "bottomRight") { image.setPosition(topLeft.getX(), topLeft.getY()); } else if(activeHandleName === "topLeft" || activeHandleName === "bottomLeft") { image.setPosition(topRight.getX() - newWidth, topRight.getY()); } 

正在更新图像位置(相对于组),但该组是具有dragBoundFunc集的组。 这解释了你的“无形边界”理论。 图像正在重新定位并在组内resize,但组位置保持静态。 拖动组时,边界与新图像大小不匹配。

您是否有理由更新这样的职位? 我评论了上面的那些线,它修复了resize然后拖动问题:你现在可以调整图像大小,拖动边界保持不变。 至少,如果你需要setPosition ,那么你应该使用group.setPosition ,并强制使用image.setPosition(0,0); 这样你只处理一个位置(图像粘在0,0左上角的组位置)。

我注意到你遇到的另一个问题是图像不能具有负宽度或高度值。 您可以通过以下方式解决此问题

image.setSize(Math.abs(newWidth), Math.abs(newHeight));

此外,由于您的图像不能具有负值,因此您必须限制您的锚点也不要相互错过。 你可以通过做一些简单的坐标检测逻辑来做到这一点:

 if(topRight.getX() < topLeft.getX()+10) { topRight.setX(topLeft.getX()+10); } if(bottomRight.getX() < topLeft.getX()+10) { bottomRight.setX(topLeft.getX()+10); } if(bottomRight.getY() < topLeft.getY()+10) { bottomRight.setY(topLeft.getY()+10); } if(bottomLeft.getY() < topLeft.getY()+10) { bottomLeft.setY(topLeft.getY()+10); } 

对于你的上一个问题:调整图像大小不应超过边界,我认为你可以简单地向你的锚点添加一个类似的dragBoundFunc 。 或者,您可以执行类似于我在本段上方处理锚点坐标逻辑的操作。 我认为dragBoundFunc方法会更干净。

这是一个更新的小提琴,虽然我没有为你的主播实现dragBoundFunc ,希望你能搞清楚!

http://jsfiddle.net/projeqht/aBkYb/

dragBoundFunc中的“pos”是组的左上角,而不是图像。

由于您在调整图像大小时没有调整组的大小,因此“pos”将始终引用组的原始大小和相对位置 – 而不是图像。

那就是抛弃你的drawBoundFunc计算。