Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<pre><code>function getSizes(baseSize, sVariance) { var sizes = []; for (i = 0; i &lt; 5; i++) { sizes[i] = Math.ceil(baseSize - (Math.random() * sVariance)); } return sizes; } function calculateOpacityValues(baseSize, sVariance) { var min = 0.25, max = 1, step = 0.75 / sVariance, i, opacityValues = {}; for (i = 0; i &lt;= sVariance; i++) { opacityValues[baseSize - i] = min + step * i; } return opacityValues; } function getOpacities(sizes, opacityValues) { // create a map of opacities // and your expected values var opacities = []; sizes.forEach(function(value, index) { opacities[index] = opacityValues[value]; }); return opacities; } var baseSize = 60, sVariance = 3, sizes = getSizes(baseSize, sVariance); console.log(sizes); // use the map to get the opacity console.log(getOpacities(sizes, calculateOpacityValues(baseSize, sVariance)));​ </code></pre> <p>​ You can see it in action <a href="http://jsfiddle.net/xMkVS/2/" rel="nofollow noreferrer">here</a>. It uses the <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/forEach" rel="nofollow noreferrer">forEach</a> construct which is not supported in older browsers, but if you need to, you'll be able to switch it to a normal for loop. I've also refactored your code a bit by moving all the generation logic in the <code>getSizes</code> method and all the opacity calculation in the <code>getOpacities</code> method.</p> <p>On a sidenote, you should use <code>console.log</code> for debugging (this logs in FireBug's console on FireFox, in the Chrome WebInspector window or in the IE development console). This is a lot better than <code>document.write</code> (<a href="https://stackoverflow.com/a/8203484/182629">this is true</a> for this case also, even if we're not talking about <code>alert</code> here).</p> <h2>Edit</h2> <p><s>You didn't mention if you want the <code>baseSize</code> and the <code>variance</code> to be variable. In that case, you should add a method to generate the opacity value map based on your logic.</s> I've added the logic you requested in the sample and I've updated the code.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload