Quick Hack To Get VerticalAlign Working On KineticJS.Text

Javascript Programming

In the jungle of Javascript 2D Canvas Libraries we have chosen KineticJS for the development of Polo. As there were so many libraries, It was a tough choice. Each library comes with their own pros and cons. We have selected KineticJS mainly for following reasons:

  • Its has got an easy api to let us draw shapes, group them together with layering support
  • Collection of rich examples, showcase of each feature give quick understanding
  • Currently under active development, so we can assume timely updates and quick issue resolution

About verticalAlign

During the development I had to place some text vertically in middle of its container. The quick way to do that could have been to set container and text-block to same size and then vertically align text in center.

But on searching I came to realize that the support for verticalAlign has been temporarily dropped from KineticJS. You can see references for the same here and here. The maintainer of KineticJS ericdrowell says that, the support for the same will be added back in the v4.3.5 release.

So in the meanwhile to solve this issue I did a quick patch in the source. Just replace following lines in KineticJS.Text drawFunc function.

// Temporary fix for verticalAlign
// this issue is set to be resolved in ver:4.3.5
// https://github.com/ericdrowell/KineticJS/issues/281
var verticalpos = 0;
if(this.attrs.verticalAlign === 'bottom') {
    verticalpos = this.getHeight() - this._getTextSize(text).height - p * 2;
}
else if(this.attrs.verticalAlign === 'middle') {
    verticalpos = (this.getHeight() - this._getTextSize(text).height - p * 2) / 2;
}

// horizontal alignment
context.save();
if(this.getAlign() === RIGHT) {
    context.translate(totalWidth - width - p * 2, verticalpos);
}
else if(this.getAlign() === CENTER) {
    context.translate((totalWidth - width - p * 2) / 2, verticalpos);
}

These lines have to come in place of horizontal alignment code. For more information please see this commit.

With this I was able to position text vertically in MIDDLE, TOP, BOTTOM. I have not submitted a pull request for the same, as I am not aware of its dependencies. Nevertheless this issue is already in the pipeline and will be resolved by, v.4.3.5.

It was a quick fix just to get this going. Hope this will help you as well.

Happy Coding :-)

Leave a Reply