More efficient way of creating CssColor instances?

50 views
Skip to first unread message

markww

unread,
Nov 12, 2012, 9:22:47 AM11/12/12
to google-we...@googlegroups.com
Hi,

I need to do some drawing on a <canvas> element, is there any better way of creating fill styles on the fly? Currently I have to do this:

    public void drawFoo(Context2d context, int r, int g, int b, int a) {
        CssColor clr = CssColor.make("rgba(" + r + "," + g + "," + b + "," a + ")");
        context.setFillStyle(clr);
        context.fillRect(10, 10, 10, 10);
    }

so every time my drawFoo() method is called, I need to create a new CssColor instance to handle the red,green,blue,alpha components passed in. I don't know how efficient it is for CssColor.make() to parse the string, also ignoring that a string object needs to be constructed in the first place each time too.

Is there any better way of creating different colors on the fly like this?

Thanks

Joseph Lust

unread,
Nov 19, 2012, 10:59:14 AM11/19/12
to google-we...@googlegroups.com
You could cache those color objects of course or just declare them as static where they are used (assuming they don't often change). That being said, are you experiencing latencies right now with your current approach?

Sincerely,
Joseph

Thomas Broyer

unread,
Nov 19, 2012, 11:55:46 AM11/19/12
to google-we...@googlegroups.com
CssColor does not parse the string, it only wraps it. FYI, CssColor.make(r, g, b) simply calls  CssColor.make("rgb(" + r + ", " + g + ", " + b + ")").
The wrapping is a no-op once compiled to JS, leaving only the String concatenation.
If you were doing the same in pure JS, you'd still have to build that string to assign it to the context's fillStyle: http://dev.w3.org/html5/2dcontext/#fill-and-stroke-styles

So no, there's no better way of doing it, because there's no other way.

Joseph Lust

unread,
Nov 19, 2012, 2:12:22 PM11/19/12
to google-we...@googlegroups.com
By better way I was referring to a case where these values are not known completely at compile time but defined dynamically at run time. In such a case, not all permutations would be preconcatentated at compile time. If the implementer found themselves wanting to speed this up they could stash the commonly used color strings (i.e. if animating a repeating color ramp) rather than making them over and over. That being said, the gains would be minimal.


Sincerely,
Joseph
Reply all
Reply to author
Forward
0 new messages