-
Notifications
You must be signed in to change notification settings - Fork 7
/
blend-mode.js
43 lines (39 loc) · 1.46 KB
/
blend-mode.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
var URLreg = /(?:\(['|"]?)(.*?)(?:['|"]?\))/;
document.addEventListener('DOMContentLoaded', function() {
var supportsBackgroundBlendMode = window.getComputedStyle(document.body).backgroundBlendMode;
if(typeof supportsBackgroundBlendMode == 'undefined') {
// TODO: maybe check for Canvas composite support?
createBlendedBackgrounds();
}
}, false);
function createBlendedBackgrounds() {
var els = document.querySelectorAll('.blend-multiply');
for(var i = 0; i < els.length; i++) {
var el = els[i];
processElement(el);
}
}
function processElement(el) {
var style = window.getComputedStyle(el);
var backgroundImageURL = URLreg.exec(style.backgroundImage)[1];
var backgroundColor = style.backgroundColor;
createBlendedBackgroundImageFromURLAndColor(backgroundImageURL, backgroundColor, function(imgData) {
el.style.backgroundImage = 'url(' + imgData + ')';
});
}
function createBlendedBackgroundImageFromURLAndColor(url, color, callback) {
var img = document.createElement('img');
img.src = url;
img.onload = function() {
var canvas = document.createElement('canvas');
canvas.width = this.naturalWidth;
canvas.height = this.naturalHeight;
var context = canvas.getContext('2d');
context.globalCompositeOperation = 'multiply'
context.drawImage(this, 0, 0);
context.fillStyle = color;
context.fillRect(0, 0, canvas.width, canvas.height);
var data = canvas.toDataURL('image/jpeg');
callback(data);
};
}