1

我想请一些帮助。在我的应用程序中,矩形需要粘在网格上。我找到了一种在拖动网格时跟随网格的解决方案,但是在调整大小的情况下,我无计可施。使用以下代码达到一个网格单元大小需要 5 个步骤:

this.selectedElement.on('transform', () => {

  let stepW = (this.blockSizeW / (this.stage.width() / 2));

  let stepH = (this.blockSizeH / (this.stage.height() / 2));

  this.selectedElement.scale({
    x: Math.round(this.selectedElement.scaleX() / stepW) * stepW,
    y: Math.round(this.selectedElement.scaleY() / stepH) * stepH,
  });

});

变换后的矩形:

此外,矩形有奇怪的行为。缩放仅适用于向右和底部方向,当我尝试拖动左侧或顶部锚点时,整个矩形移动缓慢而不是缩放。任何想法将不胜感激!

我用angular 10Konva 7.1.0

4

1 回答 1

0

对于矩形形状,当您从底部或左侧调整大小时,唯一的比例会发生变化。位置(左上角)保持在同一位置。

您还需要设置{x,y}舍入逻辑。

const GRID_SIZE = 50;

shape.on('transform', () => {
  shape.x(Math.round(shape.x() / GRID_SIZE) * GRID_SIZE);
  shape.y(Math.round(shape.y() / GRID_SIZE) * GRID_SIZE);
  

  const width = shape.width() * shape.scaleX();
  const roundedWidth = Math.round(width / GRID_SIZE) * GRID_SIZE;
  if (roundedWidth !== 0) {
    shape.scaleX(roundedWidth / shape.width())
  }

  const height = shape.height() * shape.scaleY();
  const roundedHeight = Math.round(height / GRID_SIZE) * GRID_SIZE;
  if (roundedHeight !== 0) {
    shape.scaleY(roundedHeight / shape.width())
  }
})

https://jsbin.com/wonayajone/3/edit?html,js,输出

于 2021-02-08T15:48:43.873 回答