Skip To Main Content

Find the closest Power of 2 with JavaScript

Posted by Alistair Macdonald

Jun 18 2010

One of the things I have been working on over the last couple of days, is a convenient set of functions to manipulate a Processing.js Canvas for use in the CubicVR WebGL Engine. You may already know that a OpenGL performs best with textures with 2^n (power of 2) dimensions. To minimize CPU load, We wanted a way to resize a Processing.js sketch based on it’s distance from the camera.

Why on earth would you want to do this? Well… imagine you have a 3D box spinning around on your screen. The box is far away from the camera and only takes up 16 pixels of the display. On that box you have a texture that is created on the Canvas with Processing.js. The Canvas’s default size is 256px by 256px, but there is absolutely no reason to make the processor calculate a 256×256 pixel animated texture, if the user only ever sees the texture mapped to a 16×16 pixel area.

So the ideal situation is for CubicVR to be able to hook into a Processing.js script and dynamically resize it based on it’s distance from the camera. So one thing we need to be able to do, to create this balance between performance and quality, is to know how to find the closest power of 2.

The following script demonstrates how to find the nearest power of 2 in JavaScript:


function nearestPow2( aSize ){
  return Math.pow( 2, Math.round( Math.log( aSize ) / Math.log( 2 ) ) ); 
}

nearestPow2( 127 ); //  128
nearestPow2( 180 ); //  128
nearestPow2( 200 ); //  256
nearestPow2( 256 ); //  256

I got the original algorithm from Corban Brook & NotMasterYet on the Processing.js IRC Channel who pointed me to StackOverflow, and I thought it was worth sharing, thanks guys!

Posted by
Alistair Macdonald
on June 18th, 2010

Comments

We moved off of Disqus for data privacy and consent concerns, and are currently searching for a new commenting tool.

Contact Us

We'd love to hear from you. Get in touch!