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!

## Comments

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

function nearestUpperPow2(v)

{

v–;

v|=v>>1;

v|=v>>2;

v|=v>>4;

v|=v>>8;

v|=v>>16;

return v++;

}

// ðŸ˜‰

lovely ðŸ™‚ so old school ðŸ™‚

But in chromium you need to \”return ++v;\” ðŸ™‚

Thank you.

I haven’t checked Mathieu’s solution, but I agree that a bitwise calculation is better than calling through to Math functions.

And even if you choose to go the Math route, I’d recommend making local references to reduce scope and object lookups, and bitshift 0 instead of round.

Ex:

var nearestPow2 = (function(Math){

var

pow = Math.pow,

log = Math.log;

return function nearestPow2( aSize ){

return pow( 2, ( log( aSize ) / log( 2 ) ) << 0 );

};

})(Math);

We have Math.LN2

This isn’t pretty but here it is with bitwise math (and this doesn’t depend on 32 bit integers either ðŸ˜‰ )

Personally I would probably use al’s solution for readability unless the performance of the routine was shown to matter.

This is Wrong. Check for n = 23. it closest to 16 rather than 32.