-
Notifications
You must be signed in to change notification settings - Fork 0
/
resp-sprites.js
88 lines (68 loc) · 3.38 KB
/
resp-sprites.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
/**
* Responsive Sprites Framework
* Copyright 2019 Milan Babic https://www.linkedin.com/in/milanbabic1978/
* Licensed under: SEE LICENSE IN https://github.com/1978milanbabic/responsive_sprites_framework/blob/master/LICENSE
*/
/**
* Responsive Sprites Framework
* @version 1.0.0
* @author Milan Babic https://www.linkedin.com/in/milanbabic1978/
*/
function RespSprites(Obj) {
var cssClass = Obj["cssclass"];
var img_source = Obj["img_source"];
var total_width = Obj["total_width"];
var total_height = Obj["total_height"];
var picsObjs = Obj["imgs"];
var unused = [];
this.create = function () {
for (var imgname in picsObjs) {
var curClass = cssClass + "-" + imgname;
var curElems = document.getElementsByClassName(curClass);
if (curElems && curElems.length > 0) { //element exists
for (var i = 0; i < curElems.length; i++) { //for each of that class
curElems[i].style.display = "inline-block";
var curElemDefWidth = curElems[i].offsetWidth;
var contW, defW, defH;
//find default img width and height
defW = picsObjs[imgname]["width"];
defH = picsObjs[imgname]["height"];
if (curElemDefWidth && curElemDefWidth > 0) { //predefined width in css
contW = curElemDefWidth;
} else { //default img sizes
contW = defW;
curElems[i].style.width = contW + "px";
}
//******** create inner pic elem ******
//css vars
var objW = picsObjs[imgname]["width"];
var objH = picsObjs[imgname]["height"];
var objX = picsObjs[imgname]["x"];
var objY = picsObjs[imgname]["y"];
//also usable => total_width total_height
//var spanW = 100%;
var spanH = ((objH / objW) * 100); //padding-bottom in %
var picW = ((total_width / objW) * 100); //pic width in %
//var picH = auto;
var xperc = (objX / total_width) * 100;
var yperc = (objY / total_height) * 100;
//create span element (dimensions + overflow: hidden)
var innerSpan = document.createElement("span");
innerSpan.style.cssText = "display: block; position: relative; overflow: hidden; width: 100%; height: 0; padding-bottom: " + spanH + "%";
curElems[i].appendChild(innerSpan);
//create inner pic
var innerPic = document.createElement("img");
innerPic.src = img_source;
innerPic.alt = "";
innerPic.style.cssText = "position: absolute; top: 0; left: 0; width: " + picW + "%; height: auto; transform: translate(-" + xperc + "%, -" + yperc + "%); ";
innerSpan.appendChild(innerPic);
}
} else {
unused.push(curClass);
}
}
if (unused.length > 0) {
console.log("UNUSED PICS: .", unused); //Unused Pics Log for developers
}
};
}