Konvajs:如果文本高度等于 fontSize,则文本高度不会出现在 stage.toJSON() 中

Konvajs: Text height doesn't appear in stage.toJSON() if it equals to fontSize

创建文本节点后:

const text = new Konva.Text({
  x: stage.width() / 2,
  y: stage.height() / 2,
  width: 200,
  fontSize: 30,
  height: 30,
  fill: 'green',
  text: 'Simple text'
});

其中 height 值等于 fontSize 值,那么函数 stage.toJSON() 不 return 身高 参数:

[object Object] {
  attrs: [object Object] { ... },
  children: [[object Object] {
  attrs: [object Object] { ... },
  children: [[object Object] {
  attrs: [object Object] {
    fill: "green",
    fontSize: 30,
    text: "Simple text",
    width: 200
  },
  className: "Text"
}],
  className: "Layer"
}],
  className: "Stage"
}

这是一个jsbin:http://jsbin.com/hikobiceji/1/edit?html,js,console

但是如果高度字体大小不相等:

const text = new Konva.Text({
  x: stage.width() / 2,
  y: stage.height() / 2,
  width: 200,
  fontSize: 30,
  height: 30.01,
  fill: 'green',
  text: 'Simple text'
});

然后高度参数存在:

[object Object] {
  attrs: [object Object] { ... },
  children: [[object Object] {
  attrs: [object Object] { ... },
  children: [[object Object] {
  attrs: [object Object] {
    fill: "green",
    fontSize: 30,
    height: 30.01,
    text: "Simple text",
    width: 200
  },
  className: "Text"
}],
  className: "Layer"
}],
  className: "Stage"
}

jsbin: http://jsbin.com/jiriqikeka/1/edit?html,js,console

这就是Konva序列化的内在逻辑。 Konva 正在尝试使 JSON 尽可能小。所以它不包括属性的默认值。

如果文本放在一行中,文本的高度将等于其字体大小。在你的情况下默认 getter returns 30。由于它等于您使用的值,Konva 将跳过它。