From 5146c27886e8d2d6183e856167533316c0173a7a Mon Sep 17 00:00:00 2001 From: Tj Holowaychuk Date: Mon, 8 Nov 2010 17:24:20 -0800 Subject: [PATCH] Added async toDataURL() support --- lib/canvas.js | 28 ++++++++++++++++++++++------ test/canvas.test.js | 18 ++++++++++++++++-- 2 files changed, 38 insertions(+), 8 deletions(-) diff --git a/lib/canvas.js b/lib/canvas.js index 87157ed..90c74e5 100644 --- a/lib/canvas.js +++ b/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'); + } }; diff --git a/test/canvas.test.js b/test/canvas.test.js index 498d505..44a8a43 100644 --- a/test/canvas.test.js +++ b/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); + }); } } \ No newline at end of file