zschuessler / DeltaE

CIE color difference formulas in JavaScript
http://zschuessler.github.io/DeltaE
The Unlicense
260 stars 25 forks source link

Added support for L*a*b* values being passed as Strings #8

Open mike-brady opened 5 years ago

mike-brady commented 5 years ago

Thanks for this library! I am working on a tool, that allows users to enter L*a*b* values in the browser. When passing the values directly from the input DOM elements, they are passed as Strings. This can cause some values to get concatenated instead of added together.

Example Code

var l1 = document.getElementById('someID').value;
var a1 = document.getElementById('someID').value;
var b2 = document.getElementById('someID').value;
var color1 = {L: l, A: a, B: b};
DeltaE = new dE00(color1, color2);

Result

When a new dE00 object is created this.LBar, this.aPrime1, and this.aPrime2 will concatenate the two numbers in their respective formulas resulting in them being set to NaN. This will cause dE00.getDeltaE() to also return NaN.

Lines where concatenation occurs:

// L Bar
this.LBar = (x1.L + x2.L) / 2;

...

// A Prime 1
this.aPrime1 = x1.A +
    (x1.A / 2) *
    (1 - sqrt(
        pow(this.CBar, 7) /
        (pow(this.CBar, 7) + pow(25, 7))
    ));

//A Prime 2
this.aPrime2 = x2.A +
    (x2.A / 2) *
    (1 - sqrt(
        pow(this.CBar, 7) /
        (pow(this.CBar, 7) + pow(25, 7))
    ));

Fix: Apply parseFloat() to values of x1 and x2

    function dE00(x1, x2, weights) {
        var sqrt = Math.sqrt;
        var pow = Math.pow;

+       x1.L = parseFloat(x1.L);
+       x1.A = parseFloat(x1.A);
+       x1.B = parseFloat(x1.B);
+       x2.L = parseFloat(x2.L);
+       x2.A = parseFloat(x2.A);
+       x2.B = parseFloat(x2.B);

        this.x1 = x1;
        this.x2 = x2;

        ...