Browse Source

Added async toDataURL() support

v1.x
Tj Holowaychuk 14 years ago
parent
commit
5146c27886
  1. 28
      lib/canvas.js
  2. 16
      test/canvas.test.js

28
lib/canvas.js

@ -98,17 +98,33 @@ Canvas.prototype.createSyncPNGStream = function(){
}; };
/** /**
* Return a data url. * Return a data url. Pass a function for async support.
* *
* @param {String} type * @param {String|Function} type
* @param {Function} fn
* @return {String} * @return {String}
* @api public * @api public
*/ */
Canvas.prototype.toDataURL = function(type){ Canvas.prototype.toDataURL = function(type, fn){
// TODO: jpeg / svg / pdf :) // Default to png
type = type || 'image/png'; type = type || 'image/png';
// Allow callback as first arg
if ('function' == typeof type) fn = type, type = 'image/png';
// Throw on non-png
if ('image/png' != type) throw new Error('currently only image/png is supported'); if ('image/png' != type) throw new Error('currently only image/png is supported');
return 'data:' + type
+ ';base64,' + this.toBuffer().toString('base64'); var prefix = 'data:' + type + ';base64,';
if (fn) {
this.toBuffer(function(err, buf){
if (err) return fn(err);
var str = 'data:' + type
fn(null, prefix + buf.toString('base64'));
});
} else {
return prefix + this.toBuffer().toString('base64');
}
}; };

16
test/canvas.test.js

@ -242,7 +242,7 @@ module.exports = {
assert.length(buf, 252); assert.length(buf, 252);
}, },
'test Canvas#toBuffer() async': function(assert, done){ 'test Canvas#toBuffer() async': function(assert){
new Canvas(200, 200).toBuffer(function(err, buf){ new Canvas(200, 200).toBuffer(function(err, buf){
assert.ok(!err); assert.ok(!err);
assert.equal('PNG', buf.slice(1,4).toString()); assert.equal('PNG', buf.slice(1,4).toString());
@ -279,5 +279,19 @@ module.exports = {
err = e; err = e;
} }
assert.equal('currently only image/png is supported', err.message); assert.equal('currently only image/png is supported', err.message);
},
'test Canvas#toDataURL() async': function(assert){
new Canvas(200,200).toDataURL(function(err, str){
assert.ok(!err);
assert.length(str, 358);
});
},
'test Canvas#toDataURL() async with type': function(assert){
new Canvas(200,200).toDataURL('image/png', function(err, str){
assert.ok(!err);
assert.length(str, 358);
});
} }
} }
Loading…
Cancel
Save