avp / spectra

A Javascript color library. Quickly manipulate and convert colors.
avp.github.io/spectra
MIT License
237 stars 18 forks source link

Default color doesn't take into account transparency #29

Open Azeirah opened 7 years ago

Azeirah commented 7 years ago
var color = Spectra("rgba(255, 0, 0, 0.5)");

ctx.fillStyle = color;
console.log(Spectra(ctx.fillStyle).rgbaString()); // rgba(255,0,0,1)

I would expect the last statement to print "rgba(255,0,0,0.5)".

By far the easiest fix would be to let .toString() equal .rgbaString(). A slightly more sophisticated fix would be to let .toString equal the input type:

function l(c) {
    ctx.fillStyle = c;
    console.log(Spectra(ctx.fillStyle).rgbaString());
}

var c1 = Spectra("rgb(255, 0,  0)");
var c2 = Spectra("hsl(120, 100%, 50%)");
var c3 = Spectra("rgba(255, 0, 0, 0.5)");
l(c1); // "rgb(255, 0, 0)"
l(c2); // "hsl(120, 100%, 50%)");
l(c3); // "rgba(255, 0, 0, 0.5)");
avp commented 7 years ago

I can't reproduce this; when I try that first statement (with ctx set to {}), I get the correct output.

Azeirah commented 7 years ago

@avg Oh it might actually be that I'm running an older version, I'll get back to you in a bit.

Azeirah commented 7 years ago

@avp The version was not the problem. It's important that you use an actual ctx, since assigning a Spectra color to the ctx calls .toString on that object because it expects a string, doing the same but with a plain object doesn't call toString, since nesting objects is perfectly valid.

See the following two examples, that illustrate the problem even on the currently most recent Spectra v0.2.4. The transparency of the color is definitely lost in interpretation, which is not nice :(

ctx

var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");

var color = Spectra("rgba(255, 0, 0, 0.5)");

ctx.strokeStyle = color;
console.log(ctx.strokeStyle); // expect "rgba(255,0,0,0.5)"

toString

var color = Spectra("rgba(255, 0, 0, 0.5)");
console.log(color.toString()); // expect "rgba(255,0,0,0.5)"