I have a JS library using canvas that needs to get its colors from CSS classes. The classes used by the library are predetermined, but which stylesheet (out of possibly many) is not.
With a class like this:
.a_preset_class {
margin: 10pt;
color: rgba(216,34,21,0.5);
}
I would like to be able to write something like this:
context.strokeStyle = getClassColor("a_preset_class");
and have context.strokeStyle be set to "rgba(216,34,21,0.5);"
The obvious way is to traverse document.styleSheets, but I’m hoping there’s a less drastic way that I’m unaware of.
If you are able to use Dojo in your site, you can use dojox.data.CssRuleStore to make a searchable store of all of your CSS rules. You then use the standard fetch() method to search the store, using the style rule’s “selector” property as your search term. E.g.,
Using this code as a starting point, you could create a function that takes the desired search term as its parameter, passes that in to the query, and then returns the array of CSS rules that were found. Then you can just iterate the response array after calling the function, and make whatever changes are needed.