Browse Source

Added async toDataURL() support

v1.x
Tj Holowaychuk 14 years ago
parent
commit
5146c27886
  1. 28
      lib/canvas.js
  2. 18
      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}
* @api public
*/
Canvas.prototype.toDataURL = function(type){
// TODO: jpeg / svg / pdf :)
Canvas.prototype.toDataURL = function(type, fn){
// Default to 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');
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');
}
};

18
test/canvas.test.js

@ -242,7 +242,7 @@ module.exports = {
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){
assert.ok(!err);
assert.equal('PNG', buf.slice(1,4).toString());
@ -271,7 +271,7 @@ module.exports = {
assert.equal(str, canvas.toDataURL(), 'Canvas#toDataURL() failed');
assert.equal(str, canvas.toDataURL('image/png'), 'Canvas#toDataURL() failed');
var err;
try {
canvas.toDataURL('image/jpeg');
@ -279,5 +279,19 @@ module.exports = {
err = e;
}
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