説明なし

granim.js 33KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054
  1. /*! Granim v2.0.0 - https://sarcadass.github.io/granim.js */
  2. (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  3. 'use strict';
  4. function Granim(options) {
  5. this.getElement(options.element);
  6. this.x1 = 0;
  7. this.y1 = 0;
  8. this.name = options.name || false;
  9. this.elToSetClassOn = options.elToSetClassOn || 'body';
  10. this.direction = options.direction || 'diagonal';
  11. this.customDirection = options.customDirection || {};
  12. this.validateInput('direction');
  13. this.isPausedWhenNotInView = options.isPausedWhenNotInView || false;
  14. this.states = options.states;
  15. this.stateTransitionSpeed = options.stateTransitionSpeed || 1000;
  16. this.previousTimeStamp = null;
  17. this.progress = 0;
  18. this.isPaused = false;
  19. this.isCleared = false;
  20. this.isPausedBecauseNotInView = false;
  21. this.context = this.canvas.getContext('2d');
  22. this.channels = {};
  23. this.channelsIndex = 0;
  24. this.activeState = options.defaultStateName || 'default-state';
  25. this.isChangingState = false;
  26. this.currentColors = [];
  27. this.currentColorsPos = [];
  28. this.activetransitionSpeed = null;
  29. this.eventPolyfill();
  30. this.scrollDebounceThreshold = options.scrollDebounceThreshold || 300;
  31. this.scrollDebounceTimeout = null;
  32. this.isImgLoaded = false;
  33. this.isCanvasInWindowView = false;
  34. this.firstScrollInit = true;
  35. this.animating = false;
  36. this.gradientLength = this.states[this.activeState].gradients[0].length;
  37. if (options.image && options.image.source) {
  38. this.image = {
  39. source: options.image.source,
  40. position: options.image.position || ['center', 'center'],
  41. stretchMode: options.image.stretchMode || false,
  42. blendingMode: options.image.blendingMode || false
  43. };
  44. }
  45. this.events = {
  46. start: new CustomEvent('granim:start'),
  47. end: new CustomEvent('granim:end'),
  48. gradientChange: function(details) {
  49. return new CustomEvent('granim:gradientChange', {
  50. detail: {
  51. isLooping: details.isLooping,
  52. colorsFrom: details.colorsFrom,
  53. colorsTo: details.colorsTo,
  54. activeState: details.activeState
  55. },
  56. bubbles: false,
  57. cancelable: false
  58. });
  59. }
  60. };
  61. this.callbacks = {
  62. onStart: typeof options.onStart === 'function' ? options.onStart : false,
  63. onGradientChange: typeof options.onGradientChange === 'function' ?
  64. options.onGradientChange :
  65. false,
  66. onEnd: typeof options.onEnd === 'function' ? options.onEnd : false
  67. };
  68. this.getDimensions();
  69. this.canvas.setAttribute('width', this.x1);
  70. this.canvas.setAttribute('height', this.y1);
  71. this.setColors();
  72. if (this.image) {
  73. this.validateInput('image');
  74. this.prepareImage();
  75. }
  76. this.pauseWhenNotInViewNameSpace = this.pauseWhenNotInView.bind(this);
  77. this.setSizeAttributesNameSpace = this.setSizeAttributes.bind(this);
  78. this.onResize();
  79. if (this.isPausedWhenNotInView) {
  80. this.onScroll();
  81. } else {
  82. if (!this.image) {
  83. this.refreshColorsAndPos();
  84. this.animation = requestAnimationFrame(this.animateColors.bind(this));
  85. this.animating = true;
  86. }
  87. }
  88. // Callback and Event
  89. if (this.callbacks.onStart) this.callbacks.onStart();
  90. this.canvas.dispatchEvent(this.events.start);
  91. }
  92. Granim.prototype.animateColors = require('./animateColors.js');
  93. Granim.prototype.changeBlendingMode = require('./changeBlendingMode.js');
  94. Granim.prototype.changeDirection = require('./changeDirection.js');
  95. Granim.prototype.changeState = require('./changeState.js');
  96. Granim.prototype.clear = require('./clear.js');
  97. Granim.prototype.convertColorToRgba = require('./convertColorToRgba.js');
  98. Granim.prototype.destroy = require('./destroy.js');
  99. Granim.prototype.eventPolyfill = require('./eventPolyfill.js');
  100. Granim.prototype.getColor = require('./getColor.js');
  101. Granim.prototype.getColorDiff = require('./getColorDiff.js');
  102. Granim.prototype.getColorPos = require('./getColorPos.js');
  103. Granim.prototype.getColorPosDiff = require('./getColorPosDiff.js');
  104. Granim.prototype.getCurrentColors = require('./getCurrentColors.js');
  105. Granim.prototype.getCurrentColorsPos = require('./getCurrentColorsPos.js');
  106. Granim.prototype.getDimensions = require('./getDimensions.js');
  107. Granim.prototype.getElement = require('./getElement.js');
  108. Granim.prototype.getLightness = require('./getLightness.js');
  109. Granim.prototype.makeGradient = require('./makeGradient.js');
  110. Granim.prototype.onResize = require('./onResize.js');
  111. Granim.prototype.onScroll = require('./onScroll.js');
  112. Granim.prototype.pause = require('./pause.js');
  113. Granim.prototype.pauseWhenNotInView = require('./pauseWhenNotInView.js');
  114. Granim.prototype.play = require('./play.js');
  115. Granim.prototype.prepareImage = require('./prepareImage.js');
  116. Granim.prototype.refreshColorsAndPos = require('./refreshColorsAndPos.js');
  117. Granim.prototype.setColors = require('./setColors.js');
  118. Granim.prototype.setDirection = require('./setDirection.js');
  119. Granim.prototype.setSizeAttributes = require('./setSizeAttributes.js');
  120. Granim.prototype.triggerError = require('./triggerError.js');
  121. Granim.prototype.validateInput = require('./validateInput.js');
  122. module.exports = Granim;
  123. },{"./animateColors.js":2,"./changeBlendingMode.js":3,"./changeDirection.js":4,"./changeState.js":5,"./clear.js":6,"./convertColorToRgba.js":7,"./destroy.js":8,"./eventPolyfill.js":9,"./getColor.js":10,"./getColorDiff.js":11,"./getColorPos.js":12,"./getColorPosDiff.js":13,"./getCurrentColors.js":14,"./getCurrentColorsPos.js":15,"./getDimensions.js":16,"./getElement.js":17,"./getLightness.js":18,"./makeGradient.js":19,"./onResize.js":20,"./onScroll.js":21,"./pause.js":22,"./pauseWhenNotInView.js":23,"./play.js":24,"./prepareImage.js":25,"./refreshColorsAndPos.js":26,"./setColors.js":27,"./setDirection.js":28,"./setSizeAttributes.js":29,"./triggerError.js":30,"./validateInput.js":31}],2:[function(require,module,exports){
  124. 'use strict';
  125. module.exports = function(timestamp) {
  126. var wasWindowIdled = timestamp - this.previousTimeStamp > 100;
  127. var isLoop = this.states[this.activeState].loop !== undefined ? this.states[this.activeState].loop : true;
  128. var progressPercent, isLooping, nextGradient;
  129. // If tab was inactive then resumed, reset the previous timestamp
  130. if (this.previousTimeStamp === null || wasWindowIdled) {
  131. this.previousTimeStamp = timestamp;
  132. }
  133. // Compute progress and save the timestamp
  134. this.progress = this.progress + (timestamp - this.previousTimeStamp);
  135. progressPercent = (this.progress / this.activetransitionSpeed * 100).toFixed(2);
  136. this.previousTimeStamp = timestamp;
  137. // Set the new gradient colors in a property
  138. this.refreshColorsAndPos(progressPercent);
  139. // Continue the animation or prepare for the next one
  140. if (progressPercent < 100) {
  141. this.animation = requestAnimationFrame(this.animateColors.bind(this));
  142. } else {
  143. // if the current animation index is inferior to the penultimate gradient
  144. // or to the last gradient with the loop mode activated
  145. if (this.channelsIndex < this.states[this.activeState].gradients.length - 2 || isLoop) {
  146. // Set the active transition speed to the active state one after changing state
  147. if (this.isChangingState) {
  148. this.activetransitionSpeed = this.states[this.activeState].transitionSpeed || 5000;
  149. this.isChangingState = false;
  150. }
  151. // Resetting properties
  152. this.previousTimeStamp = null;
  153. this.progress = 0;
  154. this.channelsIndex++;
  155. isLooping = false;
  156. // If it's going to loop or if it's the transition after the loop
  157. if (this.channelsIndex === this.states[this.activeState].gradients.length - 1) {
  158. isLooping = true;
  159. } else if (this.channelsIndex === this.states[this.activeState].gradients.length) {
  160. this.channelsIndex = 0;
  161. }
  162. // Checking the next gradient to send in args of an event and a callback
  163. nextGradient = this.states[this.activeState].gradients[this.channelsIndex + 1] === undefined ?
  164. this.states[this.activeState].gradients[0] :
  165. this.states[this.activeState].gradients[this.channelsIndex + 1];
  166. // Compute the colors for the transition and render a new frame
  167. this.setColors();
  168. this.animation = requestAnimationFrame(this.animateColors.bind(this));
  169. // Callback and Event
  170. if (this.callbacks.onGradientChange) {
  171. this.callbacks.onGradientChange({
  172. isLooping: isLooping,
  173. colorsFrom: this.states[this.activeState].gradients[this.channelsIndex],
  174. colorsTo: nextGradient,
  175. activeState: this.activeState
  176. });
  177. }
  178. this.canvas.dispatchEvent(this.events.gradientChange({
  179. isLooping: isLooping,
  180. colorsFrom: this.states[this.activeState].gradients[this.channelsIndex],
  181. colorsTo: nextGradient,
  182. activeState: this.activeState
  183. }));
  184. // Else if it was the last gradient on the list and the loop mode is off
  185. } else {
  186. cancelAnimationFrame(this.animation);
  187. // Callback and Event
  188. if (this.callbacks.onEnd) this.callbacks.onEnd();
  189. this.canvas.dispatchEvent(new CustomEvent('granim:end'));
  190. }
  191. }
  192. };
  193. },{}],3:[function(require,module,exports){
  194. 'use strict';
  195. module.exports = function(newBlendingMode) {
  196. this.context.clearRect(0, 0, this.x1, this.y1);
  197. this.context.globalCompositeOperation =
  198. this.image.blendingMode = newBlendingMode;
  199. this.validateInput('blendingMode');
  200. if (this.isPaused) this.refreshColorsAndPos();
  201. };
  202. },{}],4:[function(require,module,exports){
  203. 'use strict';
  204. module.exports = function(newDirection) {
  205. this.context.clearRect(0, 0, this.x1, this.y1);
  206. this.direction = newDirection;
  207. this.validateInput('direction');
  208. if (this.isPaused) this.refreshColorsAndPos();
  209. };
  210. },{}],5:[function(require,module,exports){
  211. 'use strict';
  212. module.exports = function(newState) {
  213. var _this = this;
  214. // Prevent transitioning to the same state
  215. if (this.activeState === newState) {
  216. return;
  217. }
  218. // Setting the good properties for the transition
  219. if (!this.isPaused) {
  220. this.isPaused = true;
  221. this.pause();
  222. }
  223. this.channelsIndex = -1;
  224. this.activetransitionSpeed = this.stateTransitionSpeed;
  225. this.activeColorsDiff = [];
  226. this.activeColorsPosDiff = [];
  227. this.activeColors = this.getCurrentColors();
  228. this.activeColorsPos = this.getCurrentColorsPos();
  229. this.progress = 0;
  230. this.previousTimeStamp = null;
  231. this.isChangingState = true;
  232. // Compute the gradient color and pos diff between the last frame gradient
  233. // and the first one of the new state
  234. this.states[newState].gradients[0].forEach(function(gradientColor, i, arr) {
  235. var nextColors = _this.convertColorToRgba(_this.getColor(gradientColor));
  236. var nextColorsPos = _this.getColorPos(gradientColor, i);
  237. var colorDiff = _this.getColorDiff(_this.activeColors[i], nextColors);
  238. var colorPosDiff = _this.getColorPosDiff(_this.activeColorsPos[i], nextColorsPos);
  239. _this.activeColorsDiff.push(colorDiff);
  240. _this.activeColorsPosDiff.push(colorPosDiff);
  241. });
  242. // Start the animation
  243. this.activeState = newState;
  244. this.play();
  245. };
  246. },{}],6:[function(require,module,exports){
  247. 'use strict';
  248. module.exports = function() {
  249. if (!this.isPaused) {
  250. cancelAnimationFrame(this.animation);
  251. } else {
  252. this.isPaused = false;
  253. }
  254. this.isCleared = true;
  255. this.context.clearRect(0, 0, this.x1, this.y1);
  256. };
  257. },{}],7:[function(require,module,exports){
  258. 'use strict';
  259. var regex = {
  260. hexa: /^#(?:[0-9a-fA-F]{3}){1,2}$/,
  261. rgba: /^rgba\((\d{1,3}), ?(\d{1,3}), ?(\d{1,3}), ?(.?\d{1,3})\)$/,
  262. rgb: /^rgb\((\d{1,3}), ?(\d{1,3}), ?(\d{1,3})\)$/,
  263. hsla: /^hsla\((\d{1,3}), ?(\d{1,3})%, ?(\d{1,3})%, ?(.?\d{1,3})\)$/,
  264. hsl: /^hsl\((\d{1,3}), ?(\d{1,3})%, ?(\d{1,3})%\)$/
  265. }, match;
  266. module.exports = function(color) {
  267. switch(identifyColorType(color)) {
  268. default:
  269. this.triggerError('colorType');
  270. case 'hexa':
  271. return hexToRgba(color);
  272. case 'rgba':
  273. return [
  274. parseInt(match[1], 10),
  275. parseInt(match[2], 10),
  276. parseInt(match[3], 10),
  277. parseFloat(match[4])
  278. ];
  279. case 'rgb':
  280. return [
  281. parseInt(match[1], 10),
  282. parseInt(match[2], 10),
  283. parseInt(match[3], 10),
  284. 1
  285. ];
  286. case 'hsla':
  287. return hslaToRgb(
  288. parseInt(match[1], 10) / 360,
  289. parseInt(match[2], 10) / 100,
  290. parseInt(match[3], 10) / 100,
  291. parseFloat(match[4])
  292. );
  293. case 'hsl':
  294. return hslaToRgb(
  295. parseInt(match[1], 10) / 360,
  296. parseInt(match[2], 10) / 100,
  297. parseInt(match[3], 10) / 100,
  298. 1
  299. );
  300. }
  301. };
  302. function identifyColorType(color) {
  303. var colorTypes = Object.keys(regex);
  304. var i = 0;
  305. for (i; i < colorTypes.length; i++) {
  306. match = regex[colorTypes[i]].exec(color);
  307. if (match) return colorTypes[i];
  308. }
  309. return false;
  310. }
  311. function hexToRgba(hex) {
  312. // Expand shorthand form (e.g. '03F') to full form (e.g. '0033FF')
  313. var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
  314. hex = hex.replace(shorthandRegex, function(m, r, g, b) {
  315. return r + r + g + g + b + b;
  316. });
  317. var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  318. return result ? [
  319. parseInt(result[1], 16),
  320. parseInt(result[2], 16),
  321. parseInt(result[3], 16),
  322. 1
  323. ] : null;
  324. }
  325. function hue2rgb(p, q, t) {
  326. if (t < 0) t += 1;
  327. if (t > 1) t -= 1;
  328. if (t < 1 / 6) return p + (q - p) * 6 * t;
  329. if (t < 1 / 2) return q;
  330. if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
  331. return p;
  332. }
  333. function hslaToRgb(h, s, l, a) {
  334. var r, g, b, q, p;
  335. if (s === 0) {
  336. r = g = b = l; // achromatic
  337. } else {
  338. q = l < 0.5 ? l * (1 + s) : l + s - l * s;
  339. p = 2 * l - q;
  340. r = hue2rgb(p, q, h + 1/3);
  341. g = hue2rgb(p, q, h);
  342. b = hue2rgb(p, q, h - 1/3);
  343. }
  344. return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255), a];
  345. }
  346. },{}],8:[function(require,module,exports){
  347. 'use strict';
  348. module.exports = function() {
  349. this.onResize('removeListeners');
  350. this.onScroll('removeListeners');
  351. this.clear();
  352. };
  353. },{}],9:[function(require,module,exports){
  354. 'use strict';
  355. module.exports = function() {
  356. if ( typeof window.CustomEvent === 'function' ) return;
  357. function CustomEvent(event, params) {
  358. params = params || { bubbles: false, cancelable: false, detail: undefined };
  359. var evt = document.createEvent('CustomEvent');
  360. evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
  361. return evt;
  362. }
  363. CustomEvent.prototype = window.Event.prototype;
  364. window.CustomEvent = CustomEvent;
  365. };
  366. },{}],10:[function(require,module,exports){
  367. 'use strict';
  368. module.exports = function(gradientColor) {
  369. if (typeof gradientColor === 'string') {
  370. return gradientColor;
  371. } else if (typeof gradientColor === 'object' && gradientColor.color) {
  372. return gradientColor.color;
  373. } else {
  374. this.triggerError('gradient.color');
  375. }
  376. };
  377. },{}],11:[function(require,module,exports){
  378. 'use strict';
  379. module.exports = function(colorA, colorB) {
  380. var i = 0;
  381. var colorDiff = [];
  382. for (i; i < 4; i++) {
  383. colorDiff.push(colorB[i] - colorA[i]);
  384. }
  385. return colorDiff;
  386. };
  387. },{}],12:[function(require,module,exports){
  388. 'use strict';
  389. module.exports = function(gradientColor, i) {
  390. if (typeof gradientColor === 'object' && gradientColor.pos) {
  391. return gradientColor.pos;
  392. } else {
  393. // Ensure first and last position to be 0 and 100
  394. return parseFloat(!i ? 0 : ((1 / (this.gradientLength - 1)) * i).toFixed(2));
  395. }
  396. };
  397. },{}],13:[function(require,module,exports){
  398. 'use strict';
  399. module.exports = function(posA, posB) {
  400. return posB - posA;
  401. };
  402. },{}],14:[function(require,module,exports){
  403. 'use strict';
  404. module.exports = function() {
  405. var i, j;
  406. var currentColors = [];
  407. for (i = 0; i < this.currentColors.length; i++) {
  408. currentColors.push([]);
  409. for (j = 0; j < 4; j++) {
  410. currentColors[i].push(this.currentColors[i][j]);
  411. }
  412. }
  413. // Return a deep copy of the current colors
  414. return currentColors;
  415. };
  416. },{}],15:[function(require,module,exports){
  417. 'use strict';
  418. module.exports = function() {
  419. var currentColorsPos = [], i;
  420. for (i = 0; i < this.currentColorsPos.length; i++) {
  421. currentColorsPos.push(this.currentColorsPos[i]);
  422. }
  423. // Return a deep copy of the current colors
  424. return currentColorsPos;
  425. };
  426. },{}],16:[function(require,module,exports){
  427. 'use strict';
  428. module.exports = function() {
  429. this.x1 = this.canvas.offsetWidth;
  430. this.y1 = this.canvas.offsetHeight;
  431. };
  432. },{}],17:[function(require,module,exports){
  433. 'use strict';
  434. module.exports = function(element) {
  435. if (element instanceof HTMLCanvasElement) {
  436. this.canvas = element;
  437. } else if (typeof element === 'string') {
  438. this.canvas = document.querySelector(element);
  439. } else {
  440. throw new Error('The element you used is neither a String, nor a HTMLCanvasElement');
  441. }
  442. if (!this.canvas) {
  443. throw new Error('`' + element + '` could not be found in the DOM');
  444. }
  445. };
  446. },{}],18:[function(require,module,exports){
  447. 'use strict';
  448. module.exports = function() {
  449. var currentColors = this.getCurrentColors();
  450. var gradientAverage = null;
  451. var lightnessAverage, i;
  452. var colorsAverage = currentColors.map(function(el) {
  453. // Compute the average lightness of each color
  454. // in the current gradient
  455. return Math.max(el[0], el[1], el[2]);
  456. });
  457. for (i = 0; i < colorsAverage.length; i++) {
  458. // Add all the average lightness of each color
  459. gradientAverage = gradientAverage === null ?
  460. colorsAverage[i] : gradientAverage + colorsAverage[i];
  461. if (i === colorsAverage.length - 1) {
  462. // if it's the last lightness average
  463. // divide it by the total length to
  464. // have the global average lightness
  465. lightnessAverage = Math.round(gradientAverage / (i + 1));
  466. }
  467. }
  468. return lightnessAverage >= 128 ? 'light' : 'dark';
  469. };
  470. },{}],19:[function(require,module,exports){
  471. 'use strict';
  472. module.exports = function() {
  473. var gradient = this.setDirection();
  474. var elToSetClassOnClass = document.querySelector(this.elToSetClassOn).classList;
  475. var i = 0;
  476. this.context.clearRect(0, 0, this.x1, this.y1);
  477. if (this.image) {
  478. this.context.drawImage(
  479. this.imageNode,
  480. this.imagePosition.x,
  481. this.imagePosition.y,
  482. this.imagePosition.width,
  483. this.imagePosition.height
  484. );
  485. }
  486. for (i; i < this.currentColors.length; i++) {
  487. gradient.addColorStop(this.currentColorsPos[i], 'rgba(' +
  488. this.currentColors[i][0] + ', ' +
  489. this.currentColors[i][1] + ', ' +
  490. this.currentColors[i][2] + ', ' +
  491. this.currentColors[i][3] + ')'
  492. );
  493. }
  494. if (this.name) {
  495. if (this.getLightness() === 'light') {
  496. elToSetClassOnClass.remove(this.name + '-dark');
  497. elToSetClassOnClass.add(this.name + '-light');
  498. } else {
  499. elToSetClassOnClass.remove(this.name + '-light');
  500. elToSetClassOnClass.add(this.name + '-dark');
  501. }
  502. }
  503. this.context.fillStyle = gradient;
  504. this.context.fillRect(0, 0, this.x1, this.y1);
  505. };
  506. },{}],20:[function(require,module,exports){
  507. 'use strict';
  508. module.exports = function(type) {
  509. if (type === 'removeListeners') {
  510. window.removeEventListener('resize', this.setSizeAttributesNameSpace);
  511. return;
  512. }
  513. window.addEventListener('resize', this.setSizeAttributesNameSpace);
  514. };
  515. },{}],21:[function(require,module,exports){
  516. 'use strict';
  517. module.exports = function(type) {
  518. if (type === 'removeListeners') {
  519. window.removeEventListener('scroll', this.pauseWhenNotInViewNameSpace);
  520. return;
  521. }
  522. window.addEventListener('scroll', this.pauseWhenNotInViewNameSpace);
  523. this.pauseWhenNotInViewNameSpace();
  524. };
  525. },{}],22:[function(require,module,exports){
  526. 'use strict';
  527. module.exports = function(state) {
  528. var isPausedBecauseNotInView = state === 'isPausedBecauseNotInView';
  529. if (this.isCleared) return;
  530. if (!isPausedBecauseNotInView) this.isPaused = true;
  531. cancelAnimationFrame(this.animation);
  532. this.animating = false;
  533. };
  534. },{}],23:[function(require,module,exports){
  535. 'use strict';
  536. module.exports = function() {
  537. var _this = this;
  538. if (this.scrollDebounceTimeout) clearTimeout(this.scrollDebounceTimeout);
  539. this.scrollDebounceTimeout = setTimeout(function() {
  540. var elPos = _this.canvas.getBoundingClientRect();
  541. _this.isCanvasInWindowView = !(elPos.bottom < 0 || elPos.right < 0 ||
  542. elPos.left > window.innerWidth || elPos.top > window.innerHeight);
  543. if (_this.isCanvasInWindowView) {
  544. if (!_this.isPaused || _this.firstScrollInit) {
  545. if (_this.image && !_this.isImgLoaded) {return;}
  546. _this.isPausedBecauseNotInView = false;
  547. _this.play('isPlayedBecauseInView');
  548. _this.firstScrollInit = false;
  549. }
  550. } else {
  551. if (!_this.image && _this.firstScrollInit) {
  552. _this.refreshColorsAndPos();
  553. _this.firstScrollInit = false;
  554. }
  555. if (!_this.isPaused && !_this.isPausedBecauseNotInView) {
  556. _this.isPausedBecauseNotInView = true;
  557. _this.pause('isPausedBecauseNotInView');
  558. }
  559. }
  560. }, this.scrollDebounceThreshold);
  561. };
  562. },{}],24:[function(require,module,exports){
  563. 'use strict';
  564. module.exports = function(state) {
  565. var isPlayedBecauseInView = state === 'isPlayedBecauseInView';
  566. if (!isPlayedBecauseInView) this.isPaused = false;
  567. this.isCleared = false;
  568. if (!this.animating) {
  569. this.animation = requestAnimationFrame(this.animateColors.bind(this));
  570. this.animating = true;
  571. }
  572. };
  573. },{}],25:[function(require,module,exports){
  574. 'use strict';
  575. module.exports = function() {
  576. var _this = this;
  577. if (!this.imagePosition) {
  578. this.imagePosition = { x: 0, y: 0, width: 0, height: 0 };
  579. }
  580. if (this.image.blendingMode) {
  581. this.context.globalCompositeOperation = this.image.blendingMode;
  582. }
  583. if (this.imageNode) {
  584. setImagePosition();
  585. return;
  586. }
  587. this.imageNode = new Image();
  588. this.imageNode.onerror = function() {
  589. throw new Error('Granim: The image source is invalid.');
  590. };
  591. this.imageNode.onload = function() {
  592. _this.imgOriginalWidth = _this.imageNode.width;
  593. _this.imgOriginalHeight = _this.imageNode.height;
  594. setImagePosition();
  595. _this.refreshColorsAndPos();
  596. if (!_this.isPausedWhenNotInView || _this.isCanvasInWindowView) {
  597. _this.animation = requestAnimationFrame(_this.animateColors.bind(_this));
  598. }
  599. _this.isImgLoaded = true;
  600. };
  601. this.imageNode.src = this.image.source;
  602. function setImagePosition() {
  603. var i, currentAxis;
  604. for (i = 0; i < 2; i++) {
  605. currentAxis = !i ? 'x' : 'y';
  606. setImageAxisPosition(currentAxis);
  607. }
  608. function setImageAxisPosition(axis) {
  609. var canvasWidthOrHeight = _this[axis + '1'];
  610. var imgOriginalWidthOrHeight = _this[axis === 'x' ? 'imgOriginalWidth' : 'imgOriginalHeight'];
  611. var imageAlignIndex = axis === 'x' ? _this.image.position[0] : _this.image.position[1];
  612. var imageAxisPosition;
  613. switch(imageAlignIndex) {
  614. case 'center':
  615. imageAxisPosition = imgOriginalWidthOrHeight > canvasWidthOrHeight
  616. ? -(imgOriginalWidthOrHeight - canvasWidthOrHeight) / 2
  617. : (canvasWidthOrHeight - imgOriginalWidthOrHeight) / 2;
  618. _this.imagePosition[axis] = imageAxisPosition;
  619. _this.imagePosition[axis === 'x' ? 'width' : 'height'] = imgOriginalWidthOrHeight;
  620. break;
  621. case 'top':
  622. _this.imagePosition['y'] = 0;
  623. _this.imagePosition['height'] = imgOriginalWidthOrHeight;
  624. break;
  625. case 'bottom':
  626. _this.imagePosition['y'] = canvasWidthOrHeight - imgOriginalWidthOrHeight;
  627. _this.imagePosition['height'] = imgOriginalWidthOrHeight;
  628. break;
  629. case 'right':
  630. _this.imagePosition['x'] = canvasWidthOrHeight - imgOriginalWidthOrHeight;
  631. _this.imagePosition['width'] = imgOriginalWidthOrHeight;
  632. break;
  633. case 'left':
  634. _this.imagePosition['x'] = 0;
  635. _this.imagePosition['width'] = imgOriginalWidthOrHeight;
  636. break;
  637. }
  638. if (_this.image.stretchMode) {
  639. imageAlignIndex = axis === 'x' ? _this.image.stretchMode[0] : _this.image.stretchMode[1];
  640. switch(imageAlignIndex) {
  641. case 'none':
  642. break;
  643. case 'stretch':
  644. _this.imagePosition[axis] = 0;
  645. _this.imagePosition[axis === 'x' ? 'width' : 'height'] = canvasWidthOrHeight;
  646. break;
  647. case 'stretch-if-bigger':
  648. if (imgOriginalWidthOrHeight < canvasWidthOrHeight) break;
  649. _this.imagePosition[axis] = 0;
  650. _this.imagePosition[axis === 'x' ? 'width' : 'height'] = canvasWidthOrHeight;
  651. break;
  652. case 'stretch-if-smaller':
  653. if (imgOriginalWidthOrHeight > canvasWidthOrHeight) break;
  654. _this.imagePosition[axis] = 0;
  655. _this.imagePosition[axis === 'x' ? 'width' : 'height'] = canvasWidthOrHeight;
  656. break;
  657. }
  658. }
  659. }
  660. }
  661. };
  662. },{}],26:[function(require,module,exports){
  663. 'use strict';
  664. module.exports = function(progressPercent) {
  665. var _this = this, activeChannel, activeChannelPos, i, j;
  666. // Loop through each colors of the active gradient
  667. for (i = 0; i < this.activeColors.length; i++) {
  668. // Generate RGBA colors
  669. for (j = 0; j < 4; j++) {
  670. // If color value [0-255] round to the integer,
  671. // Else if opacity [0-1] round to 2 decimals
  672. activeChannel = _this.activeColors[i][j] +
  673. (j !== 3
  674. ? Math.ceil(_this.activeColorsDiff[i][j] / 100 * progressPercent)
  675. : Math.round((_this.activeColorsDiff[i][j] / 100 * progressPercent) * 100) / 100
  676. );
  677. // Prevent colors values from going < 0 & > 255
  678. if (activeChannel <= 255 && activeChannel >= 0) {
  679. _this.currentColors[i][j] = activeChannel;
  680. }
  681. }
  682. // Generate gradient color position
  683. activeChannelPos = parseFloat((_this.activeColorsPos[i] +
  684. (_this.activeColorsPosDiff[i] / 100 * progressPercent)
  685. ).toFixed(4));
  686. if (activeChannelPos <= 1 && activeChannelPos >= 0) {
  687. _this.currentColorsPos[i] = activeChannelPos;
  688. }
  689. }
  690. this.makeGradient();
  691. };
  692. },{}],27:[function(require,module,exports){
  693. 'use strict';
  694. module.exports = function() {
  695. var _this = this, colorDiff, colorPosDiff, nextColors, nextColorsPos;
  696. if (!this.channels[this.activeState]) this.channels[this.activeState] = [];
  697. // If the actual channel exist, reassign properties and exit
  698. // (each channel is saved to prevent recomputing it each time)
  699. if (this.channels[this.activeState][this.channelsIndex] !== undefined) {
  700. this.activeColors = this.channels[this.activeState][this.channelsIndex].colors;
  701. this.activeColorsDiff = this.channels[this.activeState][this.channelsIndex].colorsDiff;
  702. this.activeColorsPos = this.channels[this.activeState][this.channelsIndex].colorsPos;
  703. this.activeColorsPosDiff = this.channels[this.activeState][this.channelsIndex].colorsPosDiff;
  704. return;
  705. }
  706. // Set blank properties
  707. this.channels[this.activeState].push([{}]);
  708. this.channels[this.activeState][this.channelsIndex].colors = [];
  709. this.channels[this.activeState][this.channelsIndex].colorsDiff = [];
  710. this.channels[this.activeState][this.channelsIndex].colorsPos = [];
  711. this.channels[this.activeState][this.channelsIndex].colorsPosDiff = [];
  712. this.activeColors = [];
  713. this.activeColorsDiff = [];
  714. this.activeColorsPos = [];
  715. this.activeColorsPosDiff = [];
  716. // Go on each gradient of the current state
  717. this.states[this.activeState].gradients[this.channelsIndex].forEach(function(color, i) {
  718. // Push the hex color converted to rgba on the channel and the active color properties
  719. var colorPos = _this.getColorPos(color, i);
  720. var color = _this.getColor(color);
  721. var rgbaColor = _this.convertColorToRgba(color);
  722. var activeChannel = _this.channels[_this.activeState];
  723. activeChannel[_this.channelsIndex].colors.push(rgbaColor);
  724. _this.activeColors.push(rgbaColor);
  725. activeChannel[_this.channelsIndex].colorsPos.push(colorPos);
  726. _this.activeColorsPos.push(colorPos);
  727. // If it's the first channel to be set, set the currentColors
  728. if (!_this.isCurrentColorsSet) {
  729. _this.currentColors.push(_this.convertColorToRgba(color));
  730. _this.currentColorsPos.push(colorPos);
  731. }
  732. // If it's the last gradient, compute the color diff between the last gradient and the first one,
  733. // else between the penultimate one and the last one
  734. if (_this.channelsIndex === _this.states[_this.activeState].gradients.length - 1) {
  735. colorDiff = _this.getColorDiff(
  736. activeChannel[_this.channelsIndex].colors[i],
  737. activeChannel[0].colors[i]
  738. );
  739. colorPosDiff = _this.getColorPosDiff(
  740. activeChannel[_this.channelsIndex].colorsPos[i],
  741. activeChannel[0].colorsPos[i]
  742. );
  743. } else {
  744. nextColors = _this.convertColorToRgba(_this.getColor(_this.states[_this.activeState].gradients[_this.channelsIndex + 1][i]));
  745. nextColorsPos = _this.getColorPos(_this.states[_this.activeState].gradients[_this.channelsIndex + 1][i], i);
  746. colorDiff = _this.getColorDiff(activeChannel[_this.channelsIndex].colors[i], nextColors);
  747. colorPosDiff = _this.getColorPosDiff(activeChannel[_this.channelsIndex].colorsPos[i], nextColorsPos);
  748. }
  749. activeChannel[_this.channelsIndex].colorsDiff.push(colorDiff);
  750. _this.activeColorsDiff.push(colorDiff);
  751. activeChannel[_this.channelsIndex].colorsPosDiff.push(colorPosDiff);
  752. _this.activeColorsPosDiff.push(colorPosDiff);
  753. });
  754. this.activetransitionSpeed = this.states[this.activeState].transitionSpeed || 5000;
  755. this.isCurrentColorsSet = true;
  756. };
  757. },{}],28:[function(require,module,exports){
  758. 'use strict';
  759. module.exports = function() {
  760. var ctx = this.context;
  761. switch(this.direction) {
  762. case 'diagonal':
  763. return ctx.createLinearGradient(0, 0, this.x1, this.y1);
  764. case 'left-right':
  765. return ctx.createLinearGradient(0, 0, this.x1, 0);
  766. case 'top-bottom':
  767. return ctx.createLinearGradient(this.x1 / 2, 0, this.x1 / 2, this.y1);
  768. case 'radial':
  769. return ctx.createRadialGradient(this.x1 / 2, this.y1 / 2, this.x1 / 2, this.x1 / 2, this.y1 / 2, 0);
  770. case 'custom':
  771. return ctx.createLinearGradient(
  772. getCustomCoordinateInPixels(this.customDirection.x0, this.x1),
  773. getCustomCoordinateInPixels(this.customDirection.y0, this.y1),
  774. getCustomCoordinateInPixels(this.customDirection.x1, this.x1),
  775. getCustomCoordinateInPixels(this.customDirection.y1, this.y1)
  776. );
  777. }
  778. };
  779. function getCustomCoordinateInPixels(coordinate, size) {
  780. return coordinate.indexOf('%') > -1
  781. ? size / 100 * parseInt(coordinate.split('%')[0], 10)
  782. : parseInt(coordinate.split('px')[0], 10);
  783. }
  784. },{}],29:[function(require,module,exports){
  785. 'use strict';
  786. module.exports = function() {
  787. this.getDimensions();
  788. this.canvas.setAttribute('width', this.x1);
  789. this.canvas.setAttribute('height', this.y1);
  790. if (this.image) this.prepareImage();
  791. this.refreshColorsAndPos();
  792. };
  793. },{}],30:[function(require,module,exports){
  794. 'use strict';
  795. module.exports = function(element) {
  796. var siteURL = 'https://sarcadass.github.io/granim.js/api.html';
  797. throw new Error('Granim: Input error on "' + element + '" option.\nCheck the API ' + siteURL + '.');
  798. };
  799. },{}],31:[function(require,module,exports){
  800. 'use strict';
  801. module.exports = function(inputType) {
  802. var xPositionValues = ['left', 'center', 'right'];
  803. var yPositionValues = ['top', 'center', 'bottom'];
  804. var stretchModeValues = ['none', 'stretch', 'stretch-if-smaller', 'stretch-if-bigger'];
  805. var blendingModeValues = ['multiply', 'screen', 'normal', 'overlay', 'darken',
  806. 'lighten', 'lighter', 'color-dodge', 'color-burn', 'hard-light', 'soft-light',
  807. 'difference', 'exclusion', 'hue', 'saturation', 'color', 'luminosity'];
  808. var directionValues = ['diagonal', 'left-right', 'top-bottom', 'radial', 'custom'];
  809. switch(inputType) {
  810. case 'image':
  811. // Validate image.position
  812. if ((!Array.isArray(this.image.position) || this.image.position.length !== 2) ||
  813. xPositionValues.indexOf(this.image.position[0]) === -1 ||
  814. yPositionValues.indexOf(this.image.position[1]) === -1
  815. ) { this.triggerError('image.position'); }
  816. // Validate image.stretchMode
  817. if (this.image.stretchMode) {
  818. if ((!Array.isArray(this.image.stretchMode) || this.image.stretchMode.length !== 2) ||
  819. stretchModeValues.indexOf(this.image.stretchMode[0]) === -1 ||
  820. stretchModeValues.indexOf(this.image.stretchMode[1]) === -1
  821. ) { this.triggerError('image.stretchMode'); }
  822. }
  823. break;
  824. case 'blendingMode':
  825. if (blendingModeValues.indexOf(this.image.blendingMode) === -1) {
  826. this.clear();
  827. this.triggerError('blendingMode');
  828. }
  829. break;
  830. case 'direction':
  831. if (directionValues.indexOf(this.direction) === -1) {
  832. this.triggerError('direction');
  833. } else {
  834. if (this.direction === 'custom') {
  835. if (!areDefinedInPixelsOrPercentage([
  836. this.customDirection.x0,
  837. this.customDirection.x1,
  838. this.customDirection.y0,
  839. this.customDirection.y1
  840. ])) {
  841. this.triggerError('customDirection');
  842. }
  843. }
  844. }
  845. break;
  846. }
  847. };
  848. function areDefinedInPixelsOrPercentage(array) {
  849. var definedInPixelsOrPercentage = true, i = 0, value;
  850. while (definedInPixelsOrPercentage && i < array.length) {
  851. value = array[i];
  852. if (typeof value !== 'string') {
  853. definedInPixelsOrPercentage = false;
  854. } else {
  855. var splittedValue = null;
  856. var unit = null;
  857. if (value.indexOf('px') !== -1) unit = 'px';
  858. if (value.indexOf('%') !== -1) unit = '%';
  859. splittedValue = value.split(unit).filter(function(value) {
  860. return value.length > 0;
  861. });
  862. // Check if there is a unit ('px' or '%'),
  863. // a char before the unit,
  864. // no char after the unit,
  865. // the string without the unit is only composed of digits
  866. if (
  867. !unit
  868. || splittedValue.length > 2
  869. || !splittedValue[0]
  870. || splittedValue[1]
  871. || !/^-?\d+\.?\d*$/.test(splittedValue[0])
  872. ) {
  873. definedInPixelsOrPercentage = false;
  874. }
  875. }
  876. i++;
  877. }
  878. return definedInPixelsOrPercentage;
  879. }
  880. },{}],32:[function(require,module,exports){
  881. window.Granim = require('./lib/Granim.js');
  882. },{"./lib/Granim.js":1}]},{},[32]);