Reputation: 26270
Consider this:
timeSeries.options.fillStyle = 'rgba(0, 255, 0, 0.2)';
In this example we are working with colour components and transparency. However from javascript perspective the right side of the expression is a string. It's just happens so, that when we later assign this string to, say, canvas context fillStyle it knows how to interpret css colour values.
But let's say that our program need to work with colours. Say, change colours rgb components or opacity.
In javascript we of course can parse the string to individual components, convert them to an object with number properties, work with these, and then convert the object back to the css colour string. This sounds like a lot of work.
Since I do not have a lot of hands-on experience in javascript I do not know what are the common idioms and patterns that make working with colours in javascript/typescript easier.
That's what I would like to know. Let's say I'd like to increase opacity of timeSeries.options.fillStyle
by 0.1. What is the easiest way to achieve that?
Upvotes: 3
Views: 75
Reputation: 21708
In javascript we of course can parse the string to individual components, convert them to an object with number properties, work with these, and then convert the object back to the css colour string. This sounds like a lot of work.
That's not a limitation of JavaScript, per se, it's simply the way Web APIs deal with colors. There are different ways to represent colors (hex, rgb, hsl) but ultimately they all are implemented as a DOMString
. Your only option here if you want to tweak properties of a color individually would be to do exactly what you outlined: serialize and deserialize an Object.
Fortunately there are libraries out there that already provide this behavior for you, such as TinyColor.
Upvotes: 1