【问题标题】:How to draw a shape with transform matrix with konva?如何使用 konva 绘制带有变换矩阵的形状?
【发布时间】:2019-08-19 01:59:19
【问题描述】:

我想用 konva 绘制一个带有变换矩阵的矩形或椭圆。但是我找不到像“setTransform”这样的函数

在我的 xml 中,我必须绘制一个包含一些信息的矩形,例如: 位置是中心点,(10,10)是矩形的左上角,(50,80)是矩形的宽度和高度。我如何使用变换矩阵来绘制矩形?

var rectObj = new Konva.Rect({
  x: 10,
  y: 10,
  width: 50,
  height: 80,
  fill: "ffff0000",
  stroke: "ffff0000"
});
//how to use the transform matrix???
return rectObj;

我想用变换矩阵画一个矩形

【问题讨论】:

  • 我的变换矩阵是 transform="0.965926,-0.258819,0.258819,0.965926,0,0"

标签: javascript konvajs


【解决方案1】:

您需要一个函数来将变换矩阵“分解”为形状的属性:

// from https://github.com/Fionoble/transformation-matrix-js/blob/fc38603c6ae43e1fde72e14bb8e22420c574eea3/src/matrix.js#L438
function decompose(me) {
  var a = me.a,
      b = me.b,
      c = me.c,
      d = me.d,
      acos = Math.acos,
      atan = Math.atan,
      sqrt = Math.sqrt,
      pi = Math.PI,

      translate = {x: me.e, y: me.f},
      rotation  = 0,
      scale     = {x: 1, y: 1},
      skew      = {x: 0, y: 0},

      determ = a * d - b * c;   // determinant(), skip DRY here...


  if (a || b) {
    var r = sqrt(a*a + b*b);
    rotation = b > 0 ? acos(a/r) : -acos(a/r);
    scale = {x:r, y:determ/r};
    skew.x = atan((a*c + b*d) / (r*r));
  }
  else if (c || d) {
    var s = sqrt(c*c + d*d);
    rotation = pi * 0.5 - (d > 0 ? acos(-c/s) : -acos(c/s));
    scale = {x:determ/s, y:s};
    skew.y = atan((a*c + b*d) / (s*s));
  }
  else { // a = b = c = d = 0
    scale = {x:0, y:0};     // = invalid matrix
  }

  return {
    scale    : scale,
    position: translate,
    rotation : rotation,
    skew     : skew
  };
}

// parse transformation string into matrix object
function parseTransform(string) {
  var parts = string.split(',');
  return {
    a: parseFloat(parts[0]),
    b: parseFloat(parts[1]),
    c: parseFloat(parts[2]),
    d: parseFloat(parts[3]),
    e: parseFloat(parts[4]),
    f: parseFloat(parts[5]), 
  }
}

然后就可以用它来申请attrs了:

var transform="0.965926,-0.258819,0.258819,0.965926,0,0";
var matrix = parseTransform(transform);
var attrs = decompose(matrix);

shape.setAttrs({
  x: attrs.position.x,
  y: attrs.position.y,
  scaleX: attrs.scale.x,
  scaleY: attrs.scale.y,
  skewX: attrs.skew.x,
  skewY: attrs.skew.y,
  rotation: attrs.rotation /  Math.PI * 180
})

演示:https://jsbin.com/bezatihoye/2/edit?js,console,output

【讨论】:

  • shape.setAttrs({ x: attrs.position.x, y: attrs.position.y, scaleX: attrs.scale.x, scaleY: attrs.scale.y, skewX: attrs.skew .x, skewY: attrs.skew.y, rotation: attrs.rotation / Math.PI * 180 }) 我认为x和y应该是原点x和y的偏移量,但是当我在transform之前有一个旋转,我应该如何改变旋转?
  • 您可以使用上面的position 来应用偏移量。这取决于您的用例。
  • 我在transform之前有一个旋转,我应该如何改变旋转?加在一起?
  • 是的,尝试这样做
猜你喜欢
  • 2013-07-28
  • 2019-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-15
  • 2016-03-23
  • 1970-01-01
  • 2012-07-24
相关资源
最近更新 更多