-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
81 lines (75 loc) · 2.15 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
'use strict';
var Promise = require('bluebird');
var Canvas = require('canvas');
var Image = Canvas.Image;
var getSmoothing = function (options) {
if (options['canvas-smoothing'] === 'false' || options['canvas-smoothing'] === false) {
return false;
}
return true;
};
var getImage = function (tile, opt) {
return new Promise(function (resolve) {
var img = new Image();
img.onload = function () {
tile.canvasImage = img;
resolve(tile);
};
img.onerror = function (err) {
opt.log.warn('Ignoring ' + tile.path + ' -> ' + err.toString() + '. Image format not supported by canvas?');
resolve();
};
img.src = tile.contents;
});
};
var resize = function (image, opt) {
return new Promise(function (resolve, reject) {
var canvas = new Canvas(opt.width, opt.height);
var ctx = canvas.getContext('2d');
ctx.imageSmoothingEnabled = getSmoothing(opt.options);
var img = new Image();
img.onload = function () {
ctx.drawImage(img, 0, 0, opt.width, opt.height);
resolve({
contents: new Buffer(canvas.toBuffer()),
type: 'png',
mimeType: 'image/png',
width: canvas.width,
height: canvas.height
});
};
img.onerror = function (err) {
opt.log.error('Error loading base image for resizing');
reject(err);
};
img.src = image.contents;
});
};
module.exports = {
create: function (tiles, opt) {
var canvas = new Canvas(opt.width, opt.height);
var ctx = canvas.getContext('2d');
ctx.imageSmoothingEnabled = getSmoothing(opt.options);
return Promise.map(tiles, function (tile) {
return getImage(tile, opt)
.then(function (t) {
if (t) {
ctx.drawImage(t.canvasImage, t.x + t.offset, t.y + t.offset);
}
return true;
});
}, {concurrency: 1})
.then(function () {
return {
contents: new Buffer(canvas.toBuffer()),
type: 'png',
mimeType: 'image/png',
width: canvas.width,
height: canvas.height
};
});
},
scale: function (base, opt) {
return resize(base, opt);
}
};