Jump to content

Text height + cocoonjs - a nice workaround based on the pixijs source code


trueicecold
 Share

Recommended Posts

So, like many others, I was stumbled with the question of how to measure text height inside cocoonjs, since text height measurement in pixijs is done with the help of DOM elements, which is not possible in CocoonJS.
My solution is simple enough - pre-populate the heightCache with the different sizes of each fonts you use. pixijs checks to see if you already tried to pull the height of a specific font style, so it doesn't need to recreate DOM elements, by keeping a heightCache array in PIXI.Text.
 
So, by utilizing the already existing code within pixijs and some simple JS code, you can generate a JS code to pre-populate this cache:
 
<html><body><div id="cache"></div><script>    var fontStyle = "font: ##px Tahoma;";    var startFontSize = 5;    var endFontSize = 10;	    for (var i=startFontSize;i<endFontSize;i++) {        var body = document.getElementsByTagName('body')[0];        var dummy = document.createElement('div');        var dummyText = document.createTextNode('M');        dummy.appendChild(dummyText);        dummy.setAttribute('style', fontStyle.replace("##", i) + ';position:absolute;top:0;left:0;');        body.appendChild(dummy);        result = dummy.offsetHeight;        document.getElementById("cache").innerHTML += "PIXI.Text.heightCache['" + fontStyle.replace("##", i) + "'] = " + result + ";<br/>";		        body.removeChild(dummy);    }</script></body></html>

it will generate:

PIXI.Text.heightCache['font: 5px Tahoma;'] = 6;PIXI.Text.heightCache['font: 6px Tahoma;'] = 7;PIXI.Text.heightCache['font: 7px Tahoma;'] = 8;PIXI.Text.heightCache['font: 8px Tahoma;'] = 10;PIXI.Text.heightCache['font: 9px Tahoma;'] = 11;

Just load it before using any text in pixijs, and you're set (as long as you use the sizes that are pre-populated).

 

I know it bloats the code a little, but it's better than not having text height in cocoonjs (2.3k for sizes 5-50)

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...