Note that there are some explanatory texts on larger screens.

plurals
  1. POStrange off-by-one issue with snippet to generate gradients
    text
    copied!<p>I use my own library for a lot of stuff, and recently I decided to add gradient functionality, but I've encountered a problem that I seem to remember having a while ago also, and this is the matter of my gradient being slightly off near the end. First, the code in question:</p> <pre><code>gradient = function(l, g) { var r = [], s = [], f = g.length - 1; for (var x = 0; x &lt; g.length; x++) g[x] = (typeof(g[x]) == 'string' ? g[x] : g[x].join(','))._replace(['#', ' ', 'rgb(', ')'], ''), g[x] = (g[x].indexOf(',') != -1 ? g[x].split(',') : g[x].chunk(2).map(function(_) { return _.fromBase('hex'); })); for (var x = 0; x &lt; f; x++) s[x] = [(g[x][0] - g[x + 1][0]) / (l - 1) * f, (g[x][1] - g[x + 1][2]) / (l - 1) * f, (g[x][2] - g[x + 1][2]) / (l - 1) * f]; for (var x = 0; x &lt; l; x++) r[x] = '', ([0, 1, 2]).map(function(_) { var c = Math.floor(x / (l / (g.length - 1))); r[x] += (g[c][_] - s[c][_] * (x - (l / (g.length - 1)) * c)).toBase('hex').pad('0', 2); }); return r; }; </code></pre> <p>And, of course, my library: <a href="http://wimg.co.uk/HJ0X8B.js" rel="nofollow noreferrer">http://wimg.co.uk/HJ0X8B.js</a></p> <p>Have fun in there! : ) If you think you might be able to help in any way at all, the custom functions I use in the gradient snippet are _replace(), chunk(), map(), and toBase() and fromBase()... as you'll be able to see at <a href="http://howironique.myartsonline.com/grad_t.html" rel="nofollow noreferrer">this demo page</a>, everything pretty much works (at least in Opera and Firefox) save for the gradient being ever so slightly off at the end (hover to be shown the hex value). For example, calling <code>gradient(50, ['ffffff', 'ffff00', '00ff00'])</code> does indeed create an array of length fifty that contains hexadecimal color values gradually shifting from red to yellow and then to lime, however the last color isn't exactly lime (in this case, it comes out 05ff00); this means that there's something slightly off in the mathematics and not the methodology.</p> <p>So... anybody willing to wade through the jungle that is the code I find so strangely beautiful to help me arrive at a solution? All assistance is greatly appreciated.</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