/
canvas.js
53 lines (43 loc) · 1.61 KB
/
canvas.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
'use strict';
var Promise = require('bluebird'),
_ = require('underscore');
module.exports = function createCanvasCompositor(Canvas) {
function readImage(rawImg) {
var image = new Canvas.Image();
image.src = rawImg.data;
return Promise.resolve({
path: rawImg.path,
width: image.width,
height: image.height,
data: image
});
}
function filterToParam(filter, canvasInstance) {
var filterMap = {
none: canvasInstance.PNG_FILTER_NONE,
sub: canvasInstance.PNG_FILTER_SUB,
up: canvasInstance.PNG_FILTER_UP,
average: canvasInstance.PNG_FILTER_AVG,
paeth: canvasInstance.PNG_FILTER_PAETH,
all: canvasInstance.PNG_ALL_FILTERS
};
return filterMap[filter];
}
function renderSprite(layout, spritePath, options) {
var canvas = new Canvas(layout.width, layout.height),
ctx = canvas.getContext('2d');
// render images to canvas
_(layout.images).each(function (image) {
ctx.drawImage(image.data, image.x, image.y, image.width, image.height);
});
// store canvas to file, we need to use this new promise because of the weird signature of toBuffer
return Promise.fromCallback(function (promiseCallback) {
return canvas.toBuffer(promiseCallback, options.compressionLevel, filterToParam(options.filter, canvas));
});
}
return {
readImage: readImage,
render: renderSprite,
filterToParam: filterToParam
};
};