-
Notifications
You must be signed in to change notification settings - Fork 0
/
diffInline.js
124 lines (98 loc) · 2.58 KB
/
diffInline.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
/**
* Протез для конструктора ImageData
*
* может принимать на вход обычные массивы, не только Uint8ClampedArray
* не работает в работниках, потому что реализован через createImageData
*/
(function (undefined) {
try {
new ImageData([], 1, 1);
}
catch (e) {
this.ImageData = function (data, width, height) {
var canvas = document.createElement('canvas');
var image = canvas.getContext('2d').createImageData(width, height);
for (var i = 0; i < data.length; i++) {
image.data[i] = data[i];
};
return image;
};
};
}).call(
'object' === typeof window && window
|| 'object' === typeof self && self
|| 'object' === typeof global && global
|| {}
);
var diffInline = (function () {
var workerPath = getCurrentWorkerPath() +'diffInline.worker.js';
var worker;
return function (images) {
var imgChecks = [];
imgChecks.push(getCheck(images[0]));
imgChecks.push(getCheck(images[1]));
worker = new Worker(workerPath);
return Promise.all(imgChecks).then(processImages);
};
// получение пути к текущему скрипту
function getCurrentWorkerPath () {
try {
var result = document.currentScript.src.split('/');
result.pop();
result = result.join('/');
result += '/';
return result;
}
catch (e) {
console.log(e);
return null;
}
};
function processImages (images) {
var img1 = getImageData(images[0]);
var img2 = getImageData(images[1]);
worker.postMessage({
old: img1,
new: img2
});
return new Promise(function (resolve, reject) {
worker.onmessage = function (e) {
e.data.diff.image = writeData(e.data);
resolve(e.data);
worker.terminate();
};
});
}
function getCheck (src) {
return new Promise(function (resolve, reject) {
var i = new Image();
i.onload = function () {
resolve(i);
};
i.src = src;
if (i.complete) {
resolve(i);
};
});
};
function getImageData (image) {
var c = document.createElement('canvas');
var cx = c.getContext('2d');
var data;
c.width = image.naturalWidth;
c.height = image.naturalHeight;
cx.drawImage(image, 0, 0);
return cx.getImageData(0, 0, c.width, c.height);
};
function writeData (diff) {
return new ImageData(diff.image, diff.width, diff.height);
};
})();
diffInline.renderResult = function (data) {
var result = document.createElement('canvas');
var resx = result.getContext('2d');
result.width = data.width;
result.height = data.height;
resx.putImageData(data, 0, 0);
return result;
};