trueicecold Posted October 10, 2014 Share Posted October 10, 2014 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) Quote Link to comment Share on other sites More sharing options...
Videlais Posted October 10, 2014 Share Posted October 10, 2014 For those interested, there is an older patch I wrote that does something like this too. Instead of pre-populating a cache, though, it draws the font to a temporary canvas, calculates its height, and then saves the value for every font requested. Quote Link to comment Share on other sites More sharing options...
agamemnus Posted October 15, 2014 Share Posted October 15, 2014 I see. IMO this would be better done and more visible in a standalone library like "CocoonJS patches" instead of adding something to pixi.js... or perhaps not. Videlais, I like your concept. Doesn't have to be CocoonJS specific though, just something that checks the height without using the DOM. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
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.