Skip to content

Commit

Permalink
Merge pull request #874 from lukechilds/async-bug
Browse files Browse the repository at this point in the history
Make sure Canvas#toDataURL is always async if a callback is passed in
  • Loading branch information
LinusU committed Feb 26, 2017
1 parent a3b53f1 commit 8586d72
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 5 deletions.
16 changes: 11 additions & 5 deletions lib/canvas.js
Expand Up @@ -247,11 +247,6 @@ Canvas.prototype.toDataURL = function(a1, a2, a3){
// ['image/jpeg', qual, fn] -> ['image/jpeg', {quality: qual}, fn]
// ['image/jpeg', undefined, fn] -> ['image/jpeg', null, fn]

if (this.width === 0 || this.height === 0) {
// Per spec, if the bitmap has no pixels, return this string:
return "data:,";
}

var type = 'image/png';
var opts = {};
var fn;
Expand Down Expand Up @@ -280,6 +275,17 @@ Canvas.prototype.toDataURL = function(a1, a2, a3){
}
}

if (this.width === 0 || this.height === 0) {
// Per spec, if the bitmap has no pixels, return this string:
var str = "data:,";
if (fn) {
setTimeout(function() {
fn(null, str);
});
}
return str;
}

if ('image/png' === type) {
if (fn) {
this.toBuffer(function(err, buf){
Expand Down
8 changes: 8 additions & 0 deletions test/canvas.test.js
Expand Up @@ -526,6 +526,14 @@ describe('Canvas', function () {
});
});

it('toDataURL(function (err, str) {...}) is async even with no canvas data', function (done) {
new Canvas().toDataURL(function(err, str){
assert.ifError(err);
assert.ok('data:,' === str);
done();
});
});

it('toDataURL(0.5, function (err, str) {...}) works and defaults to PNG', function (done) {
new Canvas(200,200).toDataURL(0.5, function(err, str){
assert.ifError(err);
Expand Down

0 comments on commit 8586d72

Please sign in to comment.