-->

Where is textBaseline in KineticJS?

2019-07-28 22:51发布

问题:

I cannot find a tutorial or documentation showing how to change canvas's textBaseline property in KineticJS. If you look in the Kinetic.Text documentation you won't find any mention of "base.." anything, and the Kinetic Text tutorial does not demonstrate its use either. Did textBaseline make it into KineticJS?

I did a jsFiddle here showing how textBaseline works on a raw canvas element, but I cannot figure out the property for doing the same thing in KineticJS. I know the documentation is rough for KineticJS; perhaps a property is there but just not mentioned?

NO - adjusting the Y coordinate is not an option due to scaling issues. Let's head that silliness off at the pass...

The following code should be placed using a bottom baseline, but as you can see in the fiddle, it uses "top".

  var text_b = new Kinetic.Text({
    x: 25,
    y: 100.5,
    text: 'Bottom',
    fontSize: 18,
    fontFamily: 'Verdana',
    fill: 'black'
  });

回答1:

I don't believe there is a KineticJS solution for textBaseline at the moment.

You'll have to use the offset method or property instead.

  • Kinetic.Shape#getOffset
  • Kinetic.Shape#getOffsetX
  • Kinetic.Shape#getOffsetY
  • Kinetic.Shape#setOffset
  • Kinetic.Shape#setOffsetX
  • Kinetic.Shape#setOffsetY

For example setting the offset property:

  var text_b = new Kinetic.Text({
    x: 25,
    y: 100.5,
    text: 'Bottom',
    fontSize: 18,
    fontFamily: 'Verdana',
    fill: 'black',
    offset: [0, 18] //Offset by full font-size
  });

  var text_m = new Kinetic.Text({
    x: 175,
    y: 100.5,
    text: 'Middle',
    fontSize: 18,
    fontFamily: 'Verdana',
    fill: 'black',
    offset: [0, 9] //Offset by half of font-size
  });

  var text_t = new Kinetic.Text({
    x: 300,
    y: 100.5,
    text: 'Top',
    fontSize: 18,
    fontFamily: 'Verdana',
    fill: 'black' //No offset, as you said the default was top alignment
  });    

In the example above I am hard-coding the offset + font-size but you can easily set these values dynamically depending on your set of fonts and font-sizes.

JSFIDDLE Note in my JSFiddle, I set the stage scale to 0.5



标签: kineticjs