1

I would like to ask for some help please. In my app the rectangles need to stick to a grid. I found a solution to follow the grid when they are dragged, but in case of resize I'm at my wit's end. It takes 5 steps to reach one grid cell size with this code:

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,
  });

});

Transformed rect:

Moreover the rect has strange behaviour. Scale only works right and bottom directions, when I try dragging the left or top anchors, the whole rectangle moves slowly instead of scaling. Any idea will be appreciated!

I use angular 10, Konva 7.1.0

lissettdm
  • 12,267
  • 1
  • 18
  • 39
catperson
  • 11
  • 1

1 Answers1

0

For the rectangle shape, when you resize from the bottom or left sides, the only scale is changing. Position (top-left corner) is staying in the same position.

You need to setup logic for {x,y} rounding too.

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,output

lavrton
  • 18,973
  • 4
  • 30
  • 63