[whatwg] setting canvas colors as array

Oliver Hunt oliver at apple.com
Sat Oct 4 15:23:21 PDT 2008


On Oct 4, 2008, at 2:53 PM, Maciej Stachowiak wrote:

> setFillColor avoid the need for allocation entirely in all cases.
>
> We could also consider letting fillStyle take a number to be  
> interpreted as a 32-bit RGBA value, since modern JS engines can do  
> math and masking faster than string operations or array allocation.  
> But the broken out setFillStyle version seems like it might still be  
> more of a perf win in many cases.

It's worth recalling that existing content (and i imagine most complex  
canvas code in general) that uses any single data structure for colour  
uses arrays so that there isn't any additional allocation.  The reason  
you see

fillStyle = "rgba("+r+","...

is because it is much easier to work with colours when keeping the  
channels as float values in [0..1], so these have to be converted to  
[0..255] values for the string which is cleaner when done over  
multiple lines -- eg

r = Math.round(colour[0] * 255);
g = Math.round(colour[1] * 255);
b = Math.round(colour[2] * 255);
fillStyle = "rgba("+r+","+g+","+b+","+colour[3]+")" // I have actually  
seen people do "rgba("+[r,g,b,colour[3]].join()+")"; because even that  
is more concise

setFillColor requires
setFillColor(color[0], color[1], color[2], color[3]);

which is still more verbose then
fillStyle = color

On Oct 4, 2008, at 8:02 AM, Kristof Zelechovski wrote:
> Instead of an array, we could also use a generic, "duck-typed"
> javascript object:
> fillStyle = {r:0, g:0.3, b: 0.6, a:1.0};
> This would seem a little clearer semantically, I think, since arrays
> are after all supposed to represent a list of semantically identical
> values.

The issue with this is that it doesn't make things much better than  
they currently are -- you end up having to convert from arrays to an  
object with named properties.  While this is nice on a conceptual  
level, it is far easier to work with colours if you just treat them as  
vectors -- by giving each channel a separately named property you  
can't trivially iterate through the channels which means you end up  
having to repeat code, and also make it impossible to just do all  
computation cleanly with "vectors", as you will eventually have to  
convert to the object form for assignment.

--Oliver



More information about the whatwg mailing list