Browse Source

Added normalizedColor() helper

v1.x
Tj Holowaychuk 15 years ago
parent
commit
ec8c3b80d9
  1. 31
      lib/canvas.js
  2. 9
      test/canvas.test.js

31
lib/canvas.js

@ -41,6 +41,32 @@ exports.cairoVersion = cairoVersion;
var cache = {};
/**
* Return a function used to normalize an RGBA color `prop`.
*
* @param {String} prop
* @return {Function}
* @api public
*/
function normalizedColor(prop) {
return function(){
var rgba = this[prop];
if (1 == rgba[3]) {
return '#'
+ rgba[0].toString(16)
+ rgba[1].toString(16)
+ rgba[2].toString(16);
} else {
return 'rgba('
+ rgba[0] + ', '
+ rgba[1] + ', '
+ rgba[2] + ', '
+ rgba[3] + ')';
}
}
}
/**
* Parse the given color `str`.
*
@ -236,10 +262,7 @@ Context2d.prototype.__defineSetter__('fillStyle', function(val){
* @api public
*/
Context2d.prototype.__defineGetter__('fillStyle', function(){
var rgba = this.lastFillStyle;
return 'rgba(' + rgba[0] + ',' + rgba[1] + ',' + rgba[2] + ',' + rgba[3] + ')';
});
Context2d.prototype.__defineGetter__('fillStyle', normalizedColor('lastFillStyle'));
/**
* Set the stroke style with the given css color string.

9
test/canvas.test.js

@ -69,11 +69,11 @@ module.exports = {
ctx.fillStyle = '#FFF';
assert.equal('#ffffff', ctx.fillStyle);
ctx.fillStyle = 'rgba(128, 200, 128, 255)';
assert.equal('#80c880ff', ctx.fillStyle);
ctx.fillStyle = 'rgba(128, 200, 128, 1)';
assert.equal('#80c880', ctx.fillStyle);
ctx.fillStyle = 'rgba(128,80,0,0.5)';
assert.equal('rgba(128, 80, 9, 0.5)', ctx.fillStyle);
assert.equal('rgba(128, 80, 0, 0.5)', ctx.fillStyle);
},
'test Canvas#getContext("2d")': function(assert){
@ -256,15 +256,12 @@ module.exports = {
ctx.fillStyle = 'rgb(0,55,0)';
ctx.fillRect(10, 10, 50, 50);
assert.equal('rgba(0,55,0,1)', ctx.fillStyle);
ctx.fillStyle = 'rgba(0,0,0,0.1)';
ctx.fillRect(60, 60, 50, 50);
assert.equal('rgba(0,0,0,0.1)', ctx.fillStyle);
ctx.fillStyle = '#000';
ctx.fillRect(110, 110, 50, 50);
assert.equal('rgba(0,0,0,1)', ctx.fillStyle);
assertChecksum(
canvas

Loading…
Cancel
Save