首页 > 解决方案 > Konvajs:如果它等于 fontSize,则文本高度不会出现在 stage.toJSON() 中

问题描述

创建文本节点后:

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

其中高度值等于fontSize值,则函数stage.toJSON()不返回高度参数:

[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

但如果heightfontSize不相等:

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

标签: konvajs

解决方案


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

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


推荐阅读