c0bra / color-scheme-js

Generate pleasant color schemes in JavaScript
http://c0bra.github.com/color-scheme-js/
MIT License
427 stars 53 forks source link

TypeErrors for certain values of hue and dist #8

Open backhand opened 8 years ago

backhand commented 8 years ago

Hi,

I'm assuming that hue should be an int between 0-255 and distance a float between 0 and 1. Given that, I've experienced the following error with various combinations of hue and distance:

TypeError: Cannot read property '0' of undefined
    at mutablecolor.ColorScheme.mutablecolor.mutablecolor.set_hue (../color-scheme/lib/color-scheme.js:505:49)
    at mutablecolor.ColorScheme.mutablecolor.mutablecolor.rotate (../color-scheme/lib/color-scheme.js:514:21)
    at Object.dispatch.triade (../color-scheme/lib/color-scheme.js:107:31)
    at ColorScheme.colors (../color-scheme/lib/color-scheme.js:134:31)

hue 170 and distance 0.16 will throw this error. This will list out some of the values:

/*jslint node:true, multistr: true */
'use strict';

var ColorScheme = require('color-scheme');

for(let hue = 0; hue < 256; hue++) {
  for(let dist = 0.0; dist < 1.0; dist+=0.01) {
    // try {
      let scheme = new ColorScheme();
      scheme.from_hue(hue)
        .scheme('triade')
        .variation('hard')
        .distance(dist);

      let colors = scheme.colors();
    } catch(err) {
      console.log(hue, dist, err);
    }
  }
}

Did I misunderstand something in the use of your library?

c0bra commented 7 years ago

@backhand sorry for taking such an extraordinarily long time to respond.

Hue should be an int between 0 and 360. The hue represents a degree around the color wheel. You can see a live version here: http://paletton.com/#uid=1000u0kllllaFw0g0qFqFg0w0aF

It seems like this is a problem with floating point imprecision in js. If you try this:

/*jslint node:true, multistr: true */
'use strict';

var ColorScheme = require('color-scheme');

for(let hue = 0; hue < 256; hue++) {
  for(let dist = 0.0; dist < 1.0; dist+=0.01) {
    try {
      let scheme = new ColorScheme();
      scheme.from_hue(hue)
        .scheme('triade')
        .variation('hard')
        .distance(dist);

      let colors = scheme.colors();
      console.log(colors[0]);
    } catch(err) {
      console.log(hue, dist, err);
    }
  }
}

You'll see that there are only errors for certain colors, not all.

And if you modify dist like this dist = dist.toFixed(2); it seems like the problem goes away.

The solution may be to just clamp distances to 2 floating points (or somewhere around there) in the library.