5

I'm try to build a Konva Text container with vertical centering of it's content;

var infoText = new Konva.Text({
  x: 0,
  y: 0,
  text: `my long long ... text`,
  fontSize: 18,
  fontFamily: 'Arial',
  width: 50,
  height: 50,
  align: 'center'
});

I found the align property in the docs, but it can only make text centered horizontally. How can I center vertically?

Vanquished Wombat
  • 9,075
  • 5
  • 28
  • 67
Littlee
  • 3,791
  • 6
  • 29
  • 61

1 Answers1

7

It is possible to do from Konva v2.3.0:

const text = new Konva.Text({
  text: 'vertical align',
  x: 20,
  height: rect.height(),
  verticalAlign: 'middle'
});

Demo: http://jsbin.com/budekuhopi/edit?html,js,output

Old answer:

At the current moment (v2.2.2), Konva can't do this automatically. You have to make manual adjustment:

const text = new Konva.Text({
  text: 'vertical align',
  x: 20,
});
layer.add(text);

text.y(containerHeight / 2 - text.getHeight() / 2);

http://jsbin.com/yakuwozaxi/2/edit?js,output

lavrton
  • 18,973
  • 4
  • 30
  • 63