温馨提示:本文翻译自stackoverflow.com,查看原文请点击:javascript - KonvaJS: how to keep the position and rotation of the shape in the group after detached?

javascript - KonvaJS:分离后如何保持形状在组中的位置和旋转?

发布于 2020-03-27 10:21:35

分离后如何在组中保持形状的位置,旋转和比例属性?

如果在用户移动或调整大小后旋转组中的每个形状,旋转包裹在Transformer下的组,则看起来形状丢失并且属性发生了更改。

我尝试以下来源。

    <button id="ungroup">ungroup</button>
    <div id="container"></div>
    const stage = new Konva.Stage({
       container: 'container',
       width: window.innerWidth,
       height: window.innerHeight
    });

    const layer = new Konva.Layer();
    stage.add(layer);

    const rect = new Konva.Rect({
       x : 50, y : 50, width: 100, height: 100,
       fill: 'black',
    });
    const rect2 = new Konva.Rect({
       x : 150, y : 50, width: 80, height: 80,
       fill: 'red',
    });

    const group = new Konva.Group({
        draggable: true
    });
    group.add(rect);
    group.add(rect2);

    const tr = new Konva.Transformer({
        node: group
    });

    layer.add(group);
    layer.add(tr);
    layer.draw();

    document.getElementById('ungroup').addEventListener('click', () => {
        tr.remove()
      // how can keep the moved or rotated properties?
      rect.moveTo(layer);
      rect2.moveTo(layer);
        group.removeChildren();
      group.remove();
      layer.draw();
    });

一个具有两个矩形的组可以与一个变压器一起移动。但是分离它们之后,它们会失去运动,缩放和旋转。

查看更多

查看更多

提问者
pius lee
被浏览
160
lavrton 2019-07-03 21:15

您可以获取节点的绝对变换矩阵,并在将其分离后重新应用到该节点。

function decompose(mat) {
  var a = mat[0];
  var b = mat[1];
  var c = mat[2];
  var d = mat[3];
  var e = mat[4];
  var f = mat[5];

  var delta = a * d - b * c;

  let result = {
    x: e,
    y: f,
    rotation: 0,
    scaleX: 0,
    scaleY: 0,
    skewX: 0,
    skewY: 0,
  };

  // Apply the QR-like decomposition.
  if (a != 0 || b != 0) {
    var r = Math.sqrt(a * a + b * b);
    result.rotation = b > 0 ? Math.acos(a / r) : -Math.acos(a / r);
    result.scaleX = r;
    result.scaleY = delta / r;
    result.skewX = Math.atan((a * c + b * d) / (r * r));
    result.scleY = 0;
  } else if (c != 0 || d != 0) {
    var s = Math.sqrt(c * c + d * d);
    result.rotation =
      Math.PI / 2 - (d > 0 ? Math.acos(-c / s) : -Math.acos(c / s));
    result.scaleX = delta / s
    result.scaleY = s;
    result.skewX = 0
    result.skewY = Math.atan((a * c + b * d) / (s * s));
  } else {
    // a = b = c = d = 0
  }

  result.rotation *= 180 / Math.PI;
  return result;
}

const matrix = node.getAbsoluteTransform().getMatrix();
const attrs = decompose(matrix);
node.moveTo(layer);
node.setAttrs(attrs);

演示:https//codepen.io/elscorpio/pen/VqvLpG

发布
问题

分享
好友

手机
浏览

扫码手机浏览