Simplify nameToRGBColor() further: No need to create function in its own scope, simply use the inject scope to contain cache and context variables.

This commit is contained in:
Jürg Lehni 2011-03-13 22:55:20 +01:00
parent 21aa12271e
commit a842b5faa6

View file

@ -15,25 +15,26 @@
*/ */
var Color = this.Color = Base.extend(new function() { var Color = this.Color = Base.extend(new function() {
var nameToRGBColor = new function() {
var cache = {}, var colorCache = {},
context; colorContext;
return function(name) {
var color = cache[name]; function nameToRGBColor(name) {
var color = colorCache[name];
if (!color) { if (!color) {
// Use a 1x1 Canvas to draw to with the given name and then // Use a 1x1 Canvas to draw to with the given name and then
// retrieve the rgb values from. Build a cache for all these // retrieve the rgb values from. Build a cache for all these
// colors on a per use basis. // colors on a per use basis.
if (!context) { if (!colorContext) {
var canvas = CanvasProvider.getCanvas(Size.create(1, 1)); var canvas = CanvasProvider.getCanvas(Size.create(1, 1));
context = canvas.getContext('2d'); colorContext = canvas.getContext('2d');
context.globalCompositeOperation = 'copy'; colorContext.globalCompositeOperation = 'copy';
} }
// Set the fillStyle of the context to the passed name // Set the fillStyle of the context to the passed name
// and fill the canvas with it. Then retrieve the first pixel: // and fill the canvas with it. Then retrieve the first pixel:
context.fillStyle = name; colorContext.fillStyle = name;
context.fillRect(0, 0, 1, 1); colorContext.fillRect(0, 0, 1, 1);
var data = context.getImageData(0, 0, 1, 1).data, var data = colorContext.getImageData(0, 0, 1, 1).data,
rgb = []; rgb = [];
for (var i = 0; i < 3; i++) for (var i = 0; i < 3; i++)
rgb[i] = data[i] / 255; rgb[i] = data[i] / 255;
@ -42,12 +43,11 @@ var Color = this.Color = Base.extend(new function() {
throw new Error('The named color "' + name throw new Error('The named color "' + name
+ '" does not exist.'); + '" does not exist.');
} else { } else {
color = cache[name] = RGBColor.read(rgb); color = colorCache[name] = RGBColor.read(rgb);
} }
} }
return color; return color;
} }
}
function hexToRGBColor(string) { function hexToRGBColor(string) {
var hex = string.match(/^#?(\w{1,2})(\w{1,2})(\w{1,2})$/); var hex = string.match(/^#?(\w{1,2})(\w{1,2})(\w{1,2})$/);