From 9835f2e9fa4d35c8e13f06d7cfdc2ade13e9eea2 Mon Sep 17 00:00:00 2001 From: fralonra Date: Thu, 7 May 2020 11:14:46 +0800 Subject: [PATCH] chore(release): v2.4.0 --- dist/lottery-wheel.js | 2140 +++++++++++++++++++++++++------------ dist/lottery-wheel.min.js | 2 +- package.json | 2 +- 3 files changed, 1448 insertions(+), 696 deletions(-) diff --git a/dist/lottery-wheel.js b/dist/lottery-wheel.js index e685e5f..439fe6b 100644 --- a/dist/lottery-wheel.js +++ b/dist/lottery-wheel.js @@ -4,15 +4,227 @@ (global = global || self, global.Wheel = factory()); }(this, (function () { 'use strict'; + function _typeof(obj) { + "@babel/helpers - typeof"; + + if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { + _typeof = function (obj) { + return typeof obj; + }; + } else { + _typeof = function (obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }; + } + + return _typeof(obj); + } + + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } + + function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } + } + + function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + return Constructor; + } + + function _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + + return obj; + } + + function ownKeys(object, enumerableOnly) { + var keys = Object.keys(object); + + if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(object); + if (enumerableOnly) symbols = symbols.filter(function (sym) { + return Object.getOwnPropertyDescriptor(object, sym).enumerable; + }); + keys.push.apply(keys, symbols); + } + + return keys; + } + + function _objectSpread2(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i] != null ? arguments[i] : {}; + + if (i % 2) { + ownKeys(Object(source), true).forEach(function (key) { + _defineProperty(target, key, source[key]); + }); + } else if (Object.getOwnPropertyDescriptors) { + Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); + } else { + ownKeys(Object(source)).forEach(function (key) { + Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); + }); + } + } + + return target; + } + + function _slicedToArray(arr, i) { + return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); + } + + function _toConsumableArray(arr) { + return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); + } + + function _arrayWithoutHoles(arr) { + if (Array.isArray(arr)) return _arrayLikeToArray(arr); + } + + function _arrayWithHoles(arr) { + if (Array.isArray(arr)) return arr; + } + + function _iterableToArray(iter) { + if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); + } + + function _iterableToArrayLimit(arr, i) { + if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; + var _arr = []; + var _n = true; + var _d = false; + var _e = undefined; + + try { + for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { + _arr.push(_s.value); + + if (i && _arr.length === i) break; + } + } catch (err) { + _d = true; + _e = err; + } finally { + try { + if (!_n && _i["return"] != null) _i["return"](); + } finally { + if (_d) throw _e; + } + } + + return _arr; + } + + function _unsupportedIterableToArray(o, minLen) { + if (!o) return; + if (typeof o === "string") return _arrayLikeToArray(o, minLen); + var n = Object.prototype.toString.call(o).slice(8, -1); + if (n === "Object" && o.constructor) n = o.constructor.name; + if (n === "Map" || n === "Set") return Array.from(o); + if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); + } + + function _arrayLikeToArray(arr, len) { + if (len == null || len > arr.length) len = arr.length; + + for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; + + return arr2; + } + + function _nonIterableSpread() { + throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); + } + + function _nonIterableRest() { + throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); + } + + function _createForOfIteratorHelper(o) { + if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { + if (Array.isArray(o) || (o = _unsupportedIterableToArray(o))) { + var i = 0; + + var F = function () {}; + + return { + s: F, + n: function () { + if (i >= o.length) return { + done: true + }; + return { + done: false, + value: o[i++] + }; + }, + e: function (e) { + throw e; + }, + f: F + }; + } + + throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); + } + + var it, + normalCompletion = true, + didErr = false, + err; + return { + s: function () { + it = o[Symbol.iterator](); + }, + n: function () { + var step = it.next(); + normalCompletion = step.done; + return step; + }, + e: function (e) { + didErr = true; + err = e; + }, + f: function () { + try { + if (!normalCompletion && it.return != null) it.return(); + } finally { + if (didErr) throw err; + } + } + }; + } + /* * anime.js v3.2.0 * (c) 2020 Julian Garnier * Released under the MIT license * animejs.com */ - // Defaults - var defaultInstanceSettings = { update: null, begin: null, @@ -27,7 +239,6 @@ autoplay: true, timelineOffset: 0 }; - var defaultTweenSettings = { duration: 1000, delay: 0, @@ -35,17 +246,12 @@ easing: 'easeOutElastic(1, .5)', round: 0 }; - - var validTransforms = ['translateX', 'translateY', 'translateZ', 'rotate', 'rotateX', 'rotateY', 'rotateZ', 'scale', 'scaleX', 'scaleY', 'scaleZ', 'skew', 'skewX', 'skewY', 'perspective', 'matrix', 'matrix3d']; - - // Caching + var validTransforms = ['translateX', 'translateY', 'translateZ', 'rotate', 'rotateX', 'rotateY', 'rotateZ', 'scale', 'scaleX', 'scaleY', 'scaleZ', 'skew', 'skewX', 'skewY', 'perspective', 'matrix', 'matrix3d']; // Caching var cache = { CSS: {}, springs: {} - }; - - // Utils + }; // Utils function minMax(val, min, max) { return Math.min(Math.max(val, min), max); @@ -60,38 +266,64 @@ } var is = { - arr: function (a) { return Array.isArray(a); }, - obj: function (a) { return stringContains(Object.prototype.toString.call(a), 'Object'); }, - pth: function (a) { return is.obj(a) && a.hasOwnProperty('totalLength'); }, - svg: function (a) { return a instanceof SVGElement; }, - inp: function (a) { return a instanceof HTMLInputElement; }, - dom: function (a) { return a.nodeType || is.svg(a); }, - str: function (a) { return typeof a === 'string'; }, - fnc: function (a) { return typeof a === 'function'; }, - und: function (a) { return typeof a === 'undefined'; }, - hex: function (a) { return /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(a); }, - rgb: function (a) { return /^rgb/.test(a); }, - hsl: function (a) { return /^hsl/.test(a); }, - col: function (a) { return (is.hex(a) || is.rgb(a) || is.hsl(a)); }, - key: function (a) { return !defaultInstanceSettings.hasOwnProperty(a) && !defaultTweenSettings.hasOwnProperty(a) && a !== 'targets' && a !== 'keyframes'; } - }; - - // Easings + arr: function arr(a) { + return Array.isArray(a); + }, + obj: function obj(a) { + return stringContains(Object.prototype.toString.call(a), 'Object'); + }, + pth: function pth(a) { + return is.obj(a) && a.hasOwnProperty('totalLength'); + }, + svg: function svg(a) { + return a instanceof SVGElement; + }, + inp: function inp(a) { + return a instanceof HTMLInputElement; + }, + dom: function dom(a) { + return a.nodeType || is.svg(a); + }, + str: function str(a) { + return typeof a === 'string'; + }, + fnc: function fnc(a) { + return typeof a === 'function'; + }, + und: function und(a) { + return typeof a === 'undefined'; + }, + hex: function hex(a) { + return /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(a); + }, + rgb: function rgb(a) { + return /^rgb/.test(a); + }, + hsl: function hsl(a) { + return /^hsl/.test(a); + }, + col: function col(a) { + return is.hex(a) || is.rgb(a) || is.hsl(a); + }, + key: function key(a) { + return !defaultInstanceSettings.hasOwnProperty(a) && !defaultTweenSettings.hasOwnProperty(a) && a !== 'targets' && a !== 'keyframes'; + } + }; // Easings function parseEasingParameters(string) { var match = /\(([^)]+)\)/.exec(string); - return match ? match[1].split(',').map(function (p) { return parseFloat(p); }) : []; - } + return match ? match[1].split(',').map(function (p) { + return parseFloat(p); + }) : []; + } // Spring solver inspired by Webkit Copyright © 2016 Apple Inc. All rights reserved. https://webkit.org/demos/spring/spring.js - // Spring solver inspired by Webkit Copyright © 2016 Apple Inc. All rights reserved. https://webkit.org/demos/spring/spring.js function spring(string, duration) { - var params = parseEasingParameters(string); var mass = minMax(is.und(params[0]) ? 1 : params[0], .1, 100); var stiffness = minMax(is.und(params[1]) ? 100 : params[1], .1, 100); var damping = minMax(is.und(params[2]) ? 10 : params[2], .1, 100); - var velocity = minMax(is.und(params[3]) ? 0 : params[3], .1, 100); + var velocity = minMax(is.und(params[3]) ? 0 : params[3], .1, 100); var w0 = Math.sqrt(stiffness / mass); var zeta = damping / (2 * Math.sqrt(stiffness * mass)); var wd = zeta < 1 ? w0 * Math.sqrt(1 - zeta * zeta) : 0; @@ -99,85 +331,126 @@ var b = zeta < 1 ? (zeta * w0 + -velocity) / wd : -velocity + w0; function solver(t) { - var progress = duration ? (duration * t) / 1000 : t; + var progress = duration ? duration * t / 1000 : t; + if (zeta < 1) { progress = Math.exp(-progress * zeta * w0) * (a * Math.cos(wd * progress) + b * Math.sin(wd * progress)); } else { progress = (a + b * progress) * Math.exp(-progress * w0); } - if (t === 0 || t === 1) { return t; } + + if (t === 0 || t === 1) { + return t; + } + return 1 - progress; } function getDuration() { var cached = cache.springs[string]; - if (cached) { return cached; } - var frame = 1/6; + + if (cached) { + return cached; + } + + var frame = 1 / 6; var elapsed = 0; var rest = 0; - while(true) { + + while (true) { elapsed += frame; + if (solver(elapsed) === 1) { rest++; - if (rest >= 16) { break; } + + if (rest >= 16) { + break; + } } else { rest = 0; } } + var duration = elapsed * frame * 1000; cache.springs[string] = duration; return duration; } return duration ? solver : getDuration; + } // Basic steps easing implementation https://developer.mozilla.org/fr/docs/Web/CSS/transition-timing-function - } - - // Basic steps easing implementation https://developer.mozilla.org/fr/docs/Web/CSS/transition-timing-function function steps(steps) { - if ( steps === void 0 ) steps = 10; - - return function (t) { return Math.ceil((minMax(t, 0.000001, 1)) * steps) * (1 / steps); }; - } - - // BezierEasing https://github.com/gre/bezier-easing + if (steps === void 0) steps = 10; + return function (t) { + return Math.ceil(minMax(t, 0.000001, 1) * steps) * (1 / steps); + }; + } // BezierEasing https://github.com/gre/bezier-easing - var bezier = (function () { + var bezier = function () { var kSplineTableSize = 11; var kSampleStepSize = 1.0 / (kSplineTableSize - 1.0); - function A(aA1, aA2) { return 1.0 - 3.0 * aA2 + 3.0 * aA1 } - function B(aA1, aA2) { return 3.0 * aA2 - 6.0 * aA1 } - function C(aA1) { return 3.0 * aA1 } + function A(aA1, aA2) { + return 1.0 - 3.0 * aA2 + 3.0 * aA1; + } + + function B(aA1, aA2) { + return 3.0 * aA2 - 6.0 * aA1; + } - function calcBezier(aT, aA1, aA2) { return ((A(aA1, aA2) * aT + B(aA1, aA2)) * aT + C(aA1)) * aT } - function getSlope(aT, aA1, aA2) { return 3.0 * A(aA1, aA2) * aT * aT + 2.0 * B(aA1, aA2) * aT + C(aA1) } + function C(aA1) { + return 3.0 * aA1; + } + + function calcBezier(aT, aA1, aA2) { + return ((A(aA1, aA2) * aT + B(aA1, aA2)) * aT + C(aA1)) * aT; + } + + function getSlope(aT, aA1, aA2) { + return 3.0 * A(aA1, aA2) * aT * aT + 2.0 * B(aA1, aA2) * aT + C(aA1); + } function binarySubdivide(aX, aA, aB, mX1, mX2) { - var currentX, currentT, i = 0; + var currentX, + currentT, + i = 0; + do { currentT = aA + (aB - aA) / 2.0; currentX = calcBezier(currentT, mX1, mX2) - aX; - if (currentX > 0.0) { aB = currentT; } else { aA = currentT; } + + if (currentX > 0.0) { + aB = currentT; + } else { + aA = currentT; + } } while (Math.abs(currentX) > 0.0000001 && ++i < 10); + return currentT; } function newtonRaphsonIterate(aX, aGuessT, mX1, mX2) { for (var i = 0; i < 4; ++i) { var currentSlope = getSlope(aGuessT, mX1, mX2); - if (currentSlope === 0.0) { return aGuessT; } + + if (currentSlope === 0.0) { + return aGuessT; + } + var currentX = calcBezier(aGuessT, mX1, mX2) - aX; aGuessT -= currentX / currentSlope; } + return aGuessT; } function bezier(mX1, mY1, mX2, mY2) { + if (!(0 <= mX1 && mX1 <= 1 && 0 <= mX2 && mX2 <= 1)) { + return; + } - if (!(0 <= mX1 && mX1 <= 1 && 0 <= mX2 && mX2 <= 1)) { return; } var sampleValues = new Float32Array(kSplineTableSize); if (mX1 !== mY1 || mX2 !== mY2) { @@ -187,7 +460,6 @@ } function getTForX(aX) { - var intervalStart = 0; var currentSample = 1; var lastSample = kSplineTableSize - 1; @@ -197,7 +469,6 @@ } --currentSample; - var dist = (aX - sampleValues[currentSample]) / (sampleValues[currentSample + 1] - sampleValues[currentSample]); var guessForT = intervalStart + dist * kSampleStepSize; var initialSlope = getSlope(guessForT, mX1, mX2); @@ -209,158 +480,224 @@ } else { return binarySubdivide(aX, intervalStart, intervalStart + kSampleStepSize, mX1, mX2); } - } return function (x) { - if (mX1 === mY1 && mX2 === mY2) { return x; } - if (x === 0 || x === 1) { return x; } - return calcBezier(getTForX(x), mY1, mY2); - } + if (mX1 === mY1 && mX2 === mY2) { + return x; + } + if (x === 0 || x === 1) { + return x; + } + + return calcBezier(getTForX(x), mY1, mY2); + }; } return bezier; + }(); - })(); - - var penner = (function () { - + var penner = function () { // Based on jQuery UI's implemenation of easing equations from Robert Penner (http://www.robertpenner.com/easing) - - var eases = { linear: function () { return function (t) { return t; }; } }; - + var eases = { + linear: function linear() { + return function (t) { + return t; + }; + } + }; var functionEasings = { - Sine: function () { return function (t) { return 1 - Math.cos(t * Math.PI / 2); }; }, - Circ: function () { return function (t) { return 1 - Math.sqrt(1 - t * t); }; }, - Back: function () { return function (t) { return t * t * (3 * t - 2); }; }, - Bounce: function () { return function (t) { - var pow2, b = 4; - while (t < (( pow2 = Math.pow(2, --b)) - 1) / 11) {} - return 1 / Math.pow(4, 3 - b) - 7.5625 * Math.pow(( pow2 * 3 - 2 ) / 22 - t, 2) - }; }, - Elastic: function (amplitude, period) { - if ( amplitude === void 0 ) amplitude = 1; - if ( period === void 0 ) period = .5; + Sine: function Sine() { + return function (t) { + return 1 - Math.cos(t * Math.PI / 2); + }; + }, + Circ: function Circ() { + return function (t) { + return 1 - Math.sqrt(1 - t * t); + }; + }, + Back: function Back() { + return function (t) { + return t * t * (3 * t - 2); + }; + }, + Bounce: function Bounce() { + return function (t) { + var pow2, + b = 4; + + while (t < ((pow2 = Math.pow(2, --b)) - 1) / 11) {} + return 1 / Math.pow(4, 3 - b) - 7.5625 * Math.pow((pow2 * 3 - 2) / 22 - t, 2); + }; + }, + Elastic: function Elastic(amplitude, period) { + if (amplitude === void 0) amplitude = 1; + if (period === void 0) period = .5; var a = minMax(amplitude, 1, 10); var p = minMax(period, .1, 2); return function (t) { - return (t === 0 || t === 1) ? t : - -a * Math.pow(2, 10 * (t - 1)) * Math.sin((((t - 1) - (p / (Math.PI * 2) * Math.asin(1 / a))) * (Math.PI * 2)) / p); - } + return t === 0 || t === 1 ? t : -a * Math.pow(2, 10 * (t - 1)) * Math.sin((t - 1 - p / (Math.PI * 2) * Math.asin(1 / a)) * (Math.PI * 2) / p); + }; } }; - var baseEasings = ['Quad', 'Cubic', 'Quart', 'Quint', 'Expo']; - baseEasings.forEach(function (name, i) { - functionEasings[name] = function () { return function (t) { return Math.pow(t, i + 2); }; }; + functionEasings[name] = function () { + return function (t) { + return Math.pow(t, i + 2); + }; + }; }); - Object.keys(functionEasings).forEach(function (name) { var easeIn = functionEasings[name]; eases['easeIn' + name] = easeIn; - eases['easeOut' + name] = function (a, b) { return function (t) { return 1 - easeIn(a, b)(1 - t); }; }; - eases['easeInOut' + name] = function (a, b) { return function (t) { return t < 0.5 ? easeIn(a, b)(t * 2) / 2 : - 1 - easeIn(a, b)(t * -2 + 2) / 2; }; }; - }); - return eases; + eases['easeOut' + name] = function (a, b) { + return function (t) { + return 1 - easeIn(a, b)(1 - t); + }; + }; - })(); + eases['easeInOut' + name] = function (a, b) { + return function (t) { + return t < 0.5 ? easeIn(a, b)(t * 2) / 2 : 1 - easeIn(a, b)(t * -2 + 2) / 2; + }; + }; + }); + return eases; + }(); function parseEasings(easing, duration) { - if (is.fnc(easing)) { return easing; } + if (is.fnc(easing)) { + return easing; + } + var name = easing.split('(')[0]; var ease = penner[name]; var args = parseEasingParameters(easing); + switch (name) { - case 'spring' : return spring(easing, duration); - case 'cubicBezier' : return applyArguments(bezier, args); - case 'steps' : return applyArguments(steps, args); - default : return applyArguments(ease, args); + case 'spring': + return spring(easing, duration); + + case 'cubicBezier': + return applyArguments(bezier, args); + + case 'steps': + return applyArguments(steps, args); + + default: + return applyArguments(ease, args); } - } + } // Strings - // Strings function selectString(str) { try { var nodes = document.querySelectorAll(str); return nodes; - } catch(e) { + } catch (e) { return; } - } + } // Arrays - // Arrays function filterArray(arr, callback) { var len = arr.length; var thisArg = arguments.length >= 2 ? arguments[1] : void 0; var result = []; + for (var i = 0; i < len; i++) { if (i in arr) { var val = arr[i]; + if (callback.call(thisArg, val, i, arr)) { result.push(val); } } } + return result; } function flattenArray(arr) { - return arr.reduce(function (a, b) { return a.concat(is.arr(b) ? flattenArray(b) : b); }, []); + return arr.reduce(function (a, b) { + return a.concat(is.arr(b) ? flattenArray(b) : b); + }, []); } function toArray(o) { - if (is.arr(o)) { return o; } - if (is.str(o)) { o = selectString(o) || o; } - if (o instanceof NodeList || o instanceof HTMLCollection) { return [].slice.call(o); } + if (is.arr(o)) { + return o; + } + + if (is.str(o)) { + o = selectString(o) || o; + } + + if (o instanceof NodeList || o instanceof HTMLCollection) { + return [].slice.call(o); + } + return [o]; } function arrayContains(arr, val) { - return arr.some(function (a) { return a === val; }); - } + return arr.some(function (a) { + return a === val; + }); + } // Objects - // Objects function cloneObject(o) { var clone = {}; - for (var p in o) { clone[p] = o[p]; } + + for (var p in o) { + clone[p] = o[p]; + } + return clone; } function replaceObjectProps(o1, o2) { var o = cloneObject(o1); - for (var p in o1) { o[p] = o2.hasOwnProperty(p) ? o2[p] : o1[p]; } + + for (var p in o1) { + o[p] = o2.hasOwnProperty(p) ? o2[p] : o1[p]; + } + return o; } function mergeObjects(o1, o2) { var o = cloneObject(o1); - for (var p in o2) { o[p] = is.und(o1[p]) ? o2[p] : o1[p]; } + + for (var p in o2) { + o[p] = is.und(o1[p]) ? o2[p] : o1[p]; + } + return o; - } + } // Colors - // Colors function rgbToRgba(rgbValue) { var rgb = /rgb\((\d+,\s*[\d]+,\s*[\d]+)\)/g.exec(rgbValue); - return rgb ? ("rgba(" + (rgb[1]) + ",1)") : rgbValue; + return rgb ? "rgba(" + rgb[1] + ",1)" : rgbValue; } function hexToRgba(hexValue) { var rgx = /^#?([a-f\d])([a-f\d])([a-f\d])$/i; - var hex = hexValue.replace(rgx, function (m, r, g, b) { return r + r + g + g + b + b; } ); + var hex = hexValue.replace(rgx, function (m, r, g, b) { + return r + r + g + g + b + b; + }); var rgb = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); var r = parseInt(rgb[1], 16); var g = parseInt(rgb[2], 16); var b = parseInt(rgb[3], 16); - return ("rgba(" + r + "," + g + "," + b + ",1)"); + return "rgba(" + r + "," + g + "," + b + ",1)"; } function hslToRgba(hslValue) { @@ -369,49 +706,85 @@ var s = parseInt(hsl[2], 10) / 100; var l = parseInt(hsl[3], 10) / 100; var a = hsl[4] || 1; + function hue2rgb(p, q, t) { - if (t < 0) { t += 1; } - if (t > 1) { t -= 1; } - if (t < 1/6) { return p + (q - p) * 6 * t; } - if (t < 1/2) { return q; } - if (t < 2/3) { return p + (q - p) * (2/3 - t) * 6; } + if (t < 0) { + t += 1; + } + + if (t > 1) { + t -= 1; + } + + if (t < 1 / 6) { + return p + (q - p) * 6 * t; + } + + if (t < 1 / 2) { + return q; + } + + if (t < 2 / 3) { + return p + (q - p) * (2 / 3 - t) * 6; + } + return p; } + var r, g, b; + if (s == 0) { r = g = b = l; } else { var q = l < 0.5 ? l * (1 + s) : l + s - l * s; var p = 2 * l - q; - r = hue2rgb(p, q, h + 1/3); + r = hue2rgb(p, q, h + 1 / 3); g = hue2rgb(p, q, h); - b = hue2rgb(p, q, h - 1/3); + b = hue2rgb(p, q, h - 1 / 3); } - return ("rgba(" + (r * 255) + "," + (g * 255) + "," + (b * 255) + "," + a + ")"); + + return "rgba(" + r * 255 + "," + g * 255 + "," + b * 255 + "," + a + ")"; } function colorToRgb(val) { - if (is.rgb(val)) { return rgbToRgba(val); } - if (is.hex(val)) { return hexToRgba(val); } - if (is.hsl(val)) { return hslToRgba(val); } - } + if (is.rgb(val)) { + return rgbToRgba(val); + } + + if (is.hex(val)) { + return hexToRgba(val); + } + + if (is.hsl(val)) { + return hslToRgba(val); + } + } // Units - // Units function getUnit(val) { var split = /[+-]?\d*\.?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?(%|px|pt|em|rem|in|cm|mm|ex|ch|pc|vw|vh|vmin|vmax|deg|rad|turn)?$/.exec(val); - if (split) { return split[1]; } + + if (split) { + return split[1]; + } } function getTransformUnit(propName) { - if (stringContains(propName, 'translate') || propName === 'perspective') { return 'px'; } - if (stringContains(propName, 'rotate') || stringContains(propName, 'skew')) { return 'deg'; } - } + if (stringContains(propName, 'translate') || propName === 'perspective') { + return 'px'; + } + + if (stringContains(propName, 'rotate') || stringContains(propName, 'skew')) { + return 'deg'; + } + } // Values - // Values function getFunctionValue(val, animatable) { - if (!is.fnc(val)) { return val; } + if (!is.fnc(val)) { + return val; + } + return val(animatable.target, animatable.id, animatable.total); } @@ -421,12 +794,20 @@ function convertPxToUnit(el, value, unit) { var valueUnit = getUnit(value); - if (arrayContains([unit, 'deg', 'rad', 'turn'], valueUnit)) { return value; } + + if (arrayContains([unit, 'deg', 'rad', 'turn'], valueUnit)) { + return value; + } + var cached = cache.CSS[value + unit]; - if (!is.und(cached)) { return cached; } + + if (!is.und(cached)) { + return cached; + } + var baseline = 100; var tempEl = document.createElement(el.tagName); - var parentEl = (el.parentNode && (el.parentNode !== document)) ? el.parentNode : document.body; + var parentEl = el.parentNode && el.parentNode !== document ? el.parentNode : document.body; parentEl.appendChild(tempEl); tempEl.style.position = 'absolute'; tempEl.style.width = baseline + unit; @@ -446,65 +827,112 @@ } function getAnimationType(el, prop) { - if (is.dom(el) && !is.inp(el) && (getAttribute(el, prop) || (is.svg(el) && el[prop]))) { return 'attribute'; } - if (is.dom(el) && arrayContains(validTransforms, prop)) { return 'transform'; } - if (is.dom(el) && (prop !== 'transform' && getCSSValue(el, prop))) { return 'css'; } - if (el[prop] != null) { return 'object'; } + if (is.dom(el) && !is.inp(el) && (getAttribute(el, prop) || is.svg(el) && el[prop])) { + return 'attribute'; + } + + if (is.dom(el) && arrayContains(validTransforms, prop)) { + return 'transform'; + } + + if (is.dom(el) && prop !== 'transform' && getCSSValue(el, prop)) { + return 'css'; + } + + if (el[prop] != null) { + return 'object'; + } } function getElementTransforms(el) { - if (!is.dom(el)) { return; } + if (!is.dom(el)) { + return; + } + var str = el.style.transform || ''; - var reg = /(\w+)\(([^)]*)\)/g; + var reg = /(\w+)\(([^)]*)\)/g; var transforms = new Map(); - var m; while (m = reg.exec(str)) { transforms.set(m[1], m[2]); } + var m; + + while (m = reg.exec(str)) { + transforms.set(m[1], m[2]); + } + return transforms; } function getTransformValue(el, propName, animatable, unit) { var defaultVal = stringContains(propName, 'scale') ? 1 : 0 + getTransformUnit(propName); var value = getElementTransforms(el).get(propName) || defaultVal; + if (animatable) { animatable.transforms.list.set(propName, value); animatable.transforms['last'] = propName; } + return unit ? convertPxToUnit(el, value, unit) : value; } function getOriginalTargetValue(target, propName, unit, animatable) { switch (getAnimationType(target, propName)) { - case 'transform': return getTransformValue(target, propName, animatable, unit); - case 'css': return getCSSValue(target, propName, unit); - case 'attribute': return getAttribute(target, propName); - default: return target[propName] || 0; + case 'transform': + return getTransformValue(target, propName, animatable, unit); + + case 'css': + return getCSSValue(target, propName, unit); + + case 'attribute': + return getAttribute(target, propName); + + default: + return target[propName] || 0; } } function getRelativeValue(to, from) { var operator = /^(\*=|\+=|-=)/.exec(to); - if (!operator) { return to; } + + if (!operator) { + return to; + } + var u = getUnit(to) || 0; var x = parseFloat(from); var y = parseFloat(to.replace(operator[0], '')); + switch (operator[0][0]) { - case '+': return x + y + u; - case '-': return x - y + u; - case '*': return x * y + u; + case '+': + return x + y + u; + + case '-': + return x - y + u; + + case '*': + return x * y + u; } } function validateValue(val, unit) { - if (is.col(val)) { return colorToRgb(val); } - if (/\s/g.test(val)) { return val; } + if (is.col(val)) { + return colorToRgb(val); + } + + if (/\s/g.test(val)) { + return val; + } + var originalUnit = getUnit(val); var unitLess = originalUnit ? val.substr(0, val.length - originalUnit.length) : val; - if (unit) { return unitLess + unit; } - return unitLess; - } - // getTotalLength() equivalent for circle, rect, polyline, polygon and line shapes + if (unit) { + return unitLess + unit; + } + + return unitLess; + } // getTotalLength() equivalent for circle, rect, polyline, polygon and line shapes // adapted from https://gist.github.com/SebLambla/3e0550c496c236709744 + function getDistance(p1, p2) { return Math.sqrt(Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2)); } @@ -514,43 +942,63 @@ } function getRectLength(el) { - return (getAttribute(el, 'width') * 2) + (getAttribute(el, 'height') * 2); + return getAttribute(el, 'width') * 2 + getAttribute(el, 'height') * 2; } function getLineLength(el) { - return getDistance( - {x: getAttribute(el, 'x1'), y: getAttribute(el, 'y1')}, - {x: getAttribute(el, 'x2'), y: getAttribute(el, 'y2')} - ); + return getDistance({ + x: getAttribute(el, 'x1'), + y: getAttribute(el, 'y1') + }, { + x: getAttribute(el, 'x2'), + y: getAttribute(el, 'y2') + }); } function getPolylineLength(el) { var points = el.points; var totalLength = 0; var previousPos; - for (var i = 0 ; i < points.numberOfItems; i++) { + + for (var i = 0; i < points.numberOfItems; i++) { var currentPos = points.getItem(i); - if (i > 0) { totalLength += getDistance(previousPos, currentPos); } + + if (i > 0) { + totalLength += getDistance(previousPos, currentPos); + } + previousPos = currentPos; } + return totalLength; } function getPolygonLength(el) { var points = el.points; return getPolylineLength(el) + getDistance(points.getItem(points.numberOfItems - 1), points.getItem(0)); - } + } // Path animation - // Path animation function getTotalLength(el) { - if (el.getTotalLength) { return el.getTotalLength(); } - switch(el.tagName.toLowerCase()) { - case 'circle': return getCircleLength(el); - case 'rect': return getRectLength(el); - case 'line': return getLineLength(el); - case 'polyline': return getPolylineLength(el); - case 'polygon': return getPolygonLength(el); + if (el.getTotalLength) { + return el.getTotalLength(); + } + + switch (el.tagName.toLowerCase()) { + case 'circle': + return getCircleLength(el); + + case 'rect': + return getRectLength(el); + + case 'line': + return getLineLength(el); + + case 'polyline': + return getPolylineLength(el); + + case 'polygon': + return getPolygonLength(el); } } @@ -558,16 +1006,20 @@ var pathLength = getTotalLength(el); el.setAttribute('stroke-dasharray', pathLength); return pathLength; - } + } // Motion path - // Motion path function getParentSvgEl(el) { var parentEl = el.parentNode; + while (is.svg(parentEl)) { - if (!is.svg(parentEl.parentNode)) { break; } + if (!is.svg(parentEl.parentNode)) { + break; + } + parentEl = parentEl.parentNode; } + return parentEl; } @@ -586,124 +1038,176 @@ y: viewBox[1] / 1, w: width / viewBox[2], h: height / viewBox[3] - } + }; } function getPath(path, percent) { var pathEl = is.str(path) ? selectString(path)[0] : path; var p = percent || 100; - return function(property) { + return function (property) { return { property: property, el: pathEl, svg: getParentSvg(pathEl), totalLength: getTotalLength(pathEl) * (p / 100) - } - } + }; + }; } function getPathProgress(path, progress) { function point(offset) { - if ( offset === void 0 ) offset = 0; - + if (offset === void 0) offset = 0; var l = progress + offset >= 1 ? progress + offset : 0; return path.el.getPointAtLength(l); } + var svg = getParentSvg(path.el, path.svg); var p = point(); var p0 = point(-1); var p1 = point(+1); + switch (path.property) { - case 'x': return (p.x - svg.x) * svg.w; - case 'y': return (p.y - svg.y) * svg.h; - case 'angle': return Math.atan2(p1.y - p0.y, p1.x - p0.x) * 180 / Math.PI; + case 'x': + return (p.x - svg.x) * svg.w; + + case 'y': + return (p.y - svg.y) * svg.h; + + case 'angle': + return Math.atan2(p1.y - p0.y, p1.x - p0.x) * 180 / Math.PI; } - } + } // Decompose value - // Decompose value function decomposeValue(val, unit) { // const rgx = /-?\d*\.?\d+/g; // handles basic numbers // const rgx = /[+-]?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/g; // handles exponents notation var rgx = /[+-]?\d*\.?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/g; // handles exponents notation - var value = validateValue((is.pth(val) ? val.totalLength : val), unit) + ''; + + var value = validateValue(is.pth(val) ? val.totalLength : val, unit) + ''; return { original: value, numbers: value.match(rgx) ? value.match(rgx).map(Number) : [0], - strings: (is.str(val) || unit) ? value.split(rgx) : [] - } - } + strings: is.str(val) || unit ? value.split(rgx) : [] + }; + } // Animatables - // Animatables function parseTargets(targets) { - var targetsArray = targets ? (flattenArray(is.arr(targets) ? targets.map(toArray) : toArray(targets))) : []; - return filterArray(targetsArray, function (item, pos, self) { return self.indexOf(item) === pos; }); + var targetsArray = targets ? flattenArray(is.arr(targets) ? targets.map(toArray) : toArray(targets)) : []; + return filterArray(targetsArray, function (item, pos, self) { + return self.indexOf(item) === pos; + }); } function getAnimatables(targets) { var parsed = parseTargets(targets); return parsed.map(function (t, i) { - return {target: t, id: i, total: parsed.length, transforms: { list: getElementTransforms(t) } }; + return { + target: t, + id: i, + total: parsed.length, + transforms: { + list: getElementTransforms(t) + } + }; }); - } + } // Properties - // Properties function normalizePropertyTweens(prop, tweenSettings) { - var settings = cloneObject(tweenSettings); - // Override duration if easing is a spring - if (/^spring/.test(settings.easing)) { settings.duration = spring(settings.easing); } + var settings = cloneObject(tweenSettings); // Override duration if easing is a spring + + if (/^spring/.test(settings.easing)) { + settings.duration = spring(settings.easing); + } + if (is.arr(prop)) { var l = prop.length; - var isFromTo = (l === 2 && !is.obj(prop[0])); + var isFromTo = l === 2 && !is.obj(prop[0]); + if (!isFromTo) { // Duration divided by the number of tweens - if (!is.fnc(tweenSettings.duration)) { settings.duration = tweenSettings.duration / l; } + if (!is.fnc(tweenSettings.duration)) { + settings.duration = tweenSettings.duration / l; + } } else { // Transform [from, to] values shorthand to a valid tween value - prop = {value: prop}; + prop = { + value: prop + }; } } + var propArray = is.arr(prop) ? prop : [prop]; return propArray.map(function (v, i) { - var obj = (is.obj(v) && !is.pth(v)) ? v : {value: v}; - // Default delay value should only be applied to the first tween - if (is.und(obj.delay)) { obj.delay = !i ? tweenSettings.delay : 0; } - // Default endDelay value should only be applied to the last tween - if (is.und(obj.endDelay)) { obj.endDelay = i === propArray.length - 1 ? tweenSettings.endDelay : 0; } + var obj = is.obj(v) && !is.pth(v) ? v : { + value: v + }; // Default delay value should only be applied to the first tween + + if (is.und(obj.delay)) { + obj.delay = !i ? tweenSettings.delay : 0; + } // Default endDelay value should only be applied to the last tween + + + if (is.und(obj.endDelay)) { + obj.endDelay = i === propArray.length - 1 ? tweenSettings.endDelay : 0; + } + return obj; - }).map(function (k) { return mergeObjects(k, settings); }); + }).map(function (k) { + return mergeObjects(k, settings); + }); } - function flattenKeyframes(keyframes) { - var propertyNames = filterArray(flattenArray(keyframes.map(function (key) { return Object.keys(key); })), function (p) { return is.key(p); }) - .reduce(function (a,b) { if (a.indexOf(b) < 0) { a.push(b); } return a; }, []); + var propertyNames = filterArray(flattenArray(keyframes.map(function (key) { + return Object.keys(key); + })), function (p) { + return is.key(p); + }).reduce(function (a, b) { + if (a.indexOf(b) < 0) { + a.push(b); + } + + return a; + }, []); var properties = {}; - var loop = function ( i ) { + + var loop = function loop(i) { var propName = propertyNames[i]; properties[propName] = keyframes.map(function (key) { var newKey = {}; + for (var p in key) { if (is.key(p)) { - if (p == propName) { newKey.value = key[p]; } + if (p == propName) { + newKey.value = key[p]; + } } else { newKey[p] = key[p]; } } + return newKey; }); }; - for (var i = 0; i < propertyNames.length; i++) loop( i ); + for (var i = 0; i < propertyNames.length; i++) { + loop(i); + } + return properties; } function getProperties(tweenSettings, params) { var properties = []; var keyframes = params.keyframes; - if (keyframes) { params = mergeObjects(flattenKeyframes(keyframes), params); } + + if (keyframes) { + params = mergeObjects(flattenKeyframes(keyframes), params); + } + for (var p in params) { if (is.key(p)) { properties.push({ @@ -712,21 +1216,30 @@ }); } } + return properties; - } + } // Tweens - // Tweens function normalizeTweenValues(tween, animatable) { var t = {}; + for (var p in tween) { var value = getFunctionValue(tween[p], animatable); + if (is.arr(value)) { - value = value.map(function (v) { return getFunctionValue(v, animatable); }); - if (value.length === 1) { value = value[0]; } + value = value.map(function (v) { + return getFunctionValue(v, animatable); + }); + + if (value.length === 1) { + value = value[0]; + } } + t[p] = value; } + t.duration = parseFloat(t.duration); t.delay = parseFloat(t.delay); return t; @@ -744,7 +1257,11 @@ var from = is.arr(tweenValue) ? tweenValue[0] : previousValue; var fromUnit = getUnit(from) || getUnit(originalValue); var unit = toUnit || fromUnit; - if (is.und(to)) { to = previousValue; } + + if (is.und(to)) { + to = previousValue; + } + tween.from = decomposeValue(from, unit); tween.to = decomposeValue(getRelativeValue(to, from), unit); tween.start = previousTween ? previousTween.end : 0; @@ -752,29 +1269,39 @@ tween.easing = parseEasings(tween.easing, tween.duration); tween.isPath = is.pth(tweenValue); tween.isColor = is.col(tween.from.original); - if (tween.isColor) { tween.round = 1; } + + if (tween.isColor) { + tween.round = 1; + } + previousTween = tween; return tween; }); - } + } // Tween progress - // Tween progress var setProgressValue = { - css: function (t, p, v) { return t.style[p] = v; }, - attribute: function (t, p, v) { return t.setAttribute(p, v); }, - object: function (t, p, v) { return t[p] = v; }, - transform: function (t, p, v, transforms, manual) { + css: function css(t, p, v) { + return t.style[p] = v; + }, + attribute: function attribute(t, p, v) { + return t.setAttribute(p, v); + }, + object: function object(t, p, v) { + return t[p] = v; + }, + transform: function transform(t, p, v, transforms, manual) { transforms.list.set(p, v); + if (p === transforms.last || manual) { var str = ''; - transforms.list.forEach(function (value, prop) { str += prop + "(" + value + ") "; }); + transforms.list.forEach(function (value, prop) { + str += prop + "(" + value + ") "; + }); t.style.transform = str; } } - }; - - // Set Value helper + }; // Set Value helper function setTargetsValue(targets, properties) { var animatables = getAnimatables(targets); @@ -790,12 +1317,12 @@ setProgressValue[animType](target, property, to, animatable.transforms, true); } }); - } + } // Animations - // Animations function createAnimation(animatable, prop) { var animType = getAnimationType(animatable.target, prop.name); + if (animType) { var tweens = normalizeTweens(prop, animatable); var lastTween = tweens[tweens.length - 1]; @@ -807,7 +1334,7 @@ duration: lastTween.end, delay: tweens[0].delay, endDelay: lastTween.endDelay - } + }; } } @@ -816,18 +1343,29 @@ return properties.map(function (prop) { return createAnimation(animatable, prop); }); - })), function (a) { return !is.und(a); }); - } + })), function (a) { + return !is.und(a); + }); + } // Create Instance - // Create Instance function getInstanceTimings(animations, tweenSettings) { var animLength = animations.length; - var getTlOffset = function (anim) { return anim.timelineOffset ? anim.timelineOffset : 0; }; + + var getTlOffset = function getTlOffset(anim) { + return anim.timelineOffset ? anim.timelineOffset : 0; + }; + var timings = {}; - timings.duration = animLength ? Math.max.apply(Math, animations.map(function (anim) { return getTlOffset(anim) + anim.duration; })) : tweenSettings.duration; - timings.delay = animLength ? Math.min.apply(Math, animations.map(function (anim) { return getTlOffset(anim) + anim.delay; })) : tweenSettings.delay; - timings.endDelay = animLength ? timings.duration - Math.max.apply(Math, animations.map(function (anim) { return getTlOffset(anim) + anim.duration - anim.endDelay; })) : tweenSettings.endDelay; + timings.duration = animLength ? Math.max.apply(Math, animations.map(function (anim) { + return getTlOffset(anim) + anim.duration; + })) : tweenSettings.duration; + timings.delay = animLength ? Math.min.apply(Math, animations.map(function (anim) { + return getTlOffset(anim) + anim.delay; + })) : tweenSettings.delay; + timings.endDelay = animLength ? timings.duration - Math.max.apply(Math, animations.map(function (anim) { + return getTlOffset(anim) + anim.duration - anim.endDelay; + })) : tweenSettings.endDelay; return timings; } @@ -851,69 +1389,82 @@ delay: timings.delay, endDelay: timings.endDelay }); - } + } // Core - // Core var activeInstances = []; var pausedInstances = []; var raf; - var engine = (function () { - function play() { + var engine = function () { + function play() { raf = requestAnimationFrame(step); } + function step(t) { var activeInstancesLength = activeInstances.length; + if (activeInstancesLength) { var i = 0; + while (i < activeInstancesLength) { var activeInstance = activeInstances[i]; + if (!activeInstance.paused) { activeInstance.tick(t); } else { var instanceIndex = activeInstances.indexOf(activeInstance); + if (instanceIndex > -1) { activeInstances.splice(instanceIndex, 1); activeInstancesLength = activeInstances.length; } } + i++; } + play(); } else { raf = cancelAnimationFrame(raf); } } + return play; - })(); + }(); function handleVisibilityChange() { if (document.hidden) { - activeInstances.forEach(function (ins) { return ins.pause(); }); + activeInstances.forEach(function (ins) { + return ins.pause(); + }); pausedInstances = activeInstances.slice(0); anime.running = activeInstances = []; } else { - pausedInstances.forEach(function (ins) { return ins.play(); }); + pausedInstances.forEach(function (ins) { + return ins.play(); + }); } } if (typeof document !== 'undefined') { document.addEventListener('visibilitychange', handleVisibilityChange); - } + } // Public Instance - // Public Instance function anime(params) { - if ( params === void 0 ) params = {}; - - - var startTime = 0, lastTime = 0, now = 0; - var children, childrenLength = 0; + if (params === void 0) params = {}; + var startTime = 0, + lastTime = 0, + now = 0; + var children, + childrenLength = 0; var resolve = null; function makePromise(instance) { - var promise = window.Promise && new Promise(function (_resolve) { return resolve = _resolve; }); + var promise = window.Promise && new Promise(function (_resolve) { + return resolve = _resolve; + }); instance.finished = promise; return promise; } @@ -923,11 +1474,15 @@ function toggleInstanceDirection() { var direction = instance.direction; + if (direction !== 'alternate') { instance.direction = direction !== 'normal' ? 'normal' : 'reverse'; } + instance.reversed = !instance.reversed; - children.forEach(function (child) { return child.reversed = instance.reversed; }); + children.forEach(function (child) { + return child.reversed = instance.reversed; + }); } function adjustTime(time) { @@ -940,14 +1495,20 @@ } function seekChild(time, child) { - if (child) { child.seek(time - child.timelineOffset); } + if (child) { + child.seek(time - child.timelineOffset); + } } function syncInstanceChildren(time) { if (!instance.reversePlayback) { - for (var i = 0; i < childrenLength; i++) { seekChild(time, children[i]); } + for (var i = 0; i < childrenLength; i++) { + seekChild(time, children[i]); + } } else { - for (var i$1 = childrenLength; i$1--;) { seekChild(time, children[i$1]); } + for (var i$1 = childrenLength; i$1--;) { + seekChild(time, children[i$1]); + } } } @@ -955,47 +1516,61 @@ var i = 0; var animations = instance.animations; var animationsLength = animations.length; + while (i < animationsLength) { var anim = animations[i]; var animatable = anim.animatable; var tweens = anim.tweens; var tweenLength = tweens.length - 1; - var tween = tweens[tweenLength]; - // Only check for keyframes if there is more than one tween - if (tweenLength) { tween = filterArray(tweens, function (t) { return (insTime < t.end); })[0] || tween; } + var tween = tweens[tweenLength]; // Only check for keyframes if there is more than one tween + + if (tweenLength) { + tween = filterArray(tweens, function (t) { + return insTime < t.end; + })[0] || tween; + } + var elapsed = minMax(insTime - tween.start - tween.delay, 0, tween.duration) / tween.duration; var eased = isNaN(elapsed) ? 1 : tween.easing(elapsed); var strings = tween.to.strings; var round = tween.round; var numbers = []; var toNumbersLength = tween.to.numbers.length; - var progress = (void 0); + var progress = void 0; + for (var n = 0; n < toNumbersLength; n++) { - var value = (void 0); + var value = void 0; var toNumber = tween.to.numbers[n]; var fromNumber = tween.from.numbers[n] || 0; + if (!tween.isPath) { - value = fromNumber + (eased * (toNumber - fromNumber)); + value = fromNumber + eased * (toNumber - fromNumber); } else { value = getPathProgress(tween.value, eased * toNumber); } + if (round) { if (!(tween.isColor && n > 2)) { value = Math.round(value * round) / round; } } + numbers.push(value); - } - // Manual Array.reduce for better performances + } // Manual Array.reduce for better performances + + var stringsLength = strings.length; + if (!stringsLength) { progress = numbers[0]; } else { progress = strings[0]; + for (var s = 0; s < stringsLength; s++) { var a = strings[s]; var b = strings[s + 1]; var n$1 = numbers[s]; + if (!isNaN(n$1)) { if (!b) { progress += n$1 + ' '; @@ -1005,6 +1580,7 @@ } } } + setProgressValue[anim.type](animatable.target, anim.property, progress, animatable.transforms); anim.currentValue = progress; i++; @@ -1012,7 +1588,9 @@ } function setCallback(cb) { - if (instance[cb] && !instance.passThrough) { instance[cb](instance); } + if (instance[cb] && !instance.passThrough) { + instance[cb](instance); + } } function countIteration() { @@ -1026,29 +1604,38 @@ var insDelay = instance.delay; var insEndDelay = insDuration - instance.endDelay; var insTime = adjustTime(engineTime); - instance.progress = minMax((insTime / insDuration) * 100, 0, 100); + instance.progress = minMax(insTime / insDuration * 100, 0, 100); instance.reversePlayback = insTime < instance.currentTime; - if (children) { syncInstanceChildren(insTime); } + + if (children) { + syncInstanceChildren(insTime); + } + if (!instance.began && instance.currentTime > 0) { instance.began = true; setCallback('begin'); } + if (!instance.loopBegan && instance.currentTime > 0) { instance.loopBegan = true; setCallback('loopBegin'); } + if (insTime <= insDelay && instance.currentTime !== 0) { setAnimationsProgress(0); } - if ((insTime >= insEndDelay && instance.currentTime !== insDuration) || !insDuration) { + + if (insTime >= insEndDelay && instance.currentTime !== insDuration || !insDuration) { setAnimationsProgress(insDuration); } + if (insTime > insDelay && insTime < insEndDelay) { if (!instance.changeBegan) { instance.changeBegan = true; instance.changeCompleted = false; setCallback('changeBegin'); } + setCallback('change'); setAnimationsProgress(insTime); } else { @@ -1058,17 +1645,25 @@ setCallback('changeComplete'); } } + instance.currentTime = minMax(insTime, 0, insDuration); - if (instance.began) { setCallback('update'); } + + if (instance.began) { + setCallback('update'); + } + if (engineTime >= insDuration) { lastTime = 0; countIteration(); + if (!instance.remaining) { instance.paused = true; + if (!instance.completed) { instance.completed = true; setCallback('loopComplete'); setCallback('complete'); + if (!instance.passThrough && 'Promise' in window) { resolve(); promise = makePromise(instance); @@ -1078,6 +1673,7 @@ startTime = now; setCallback('loopComplete'); instance.loopBegan = false; + if (instance.direction === 'alternate') { toggleInstanceDirection(); } @@ -1085,7 +1681,7 @@ } } - instance.reset = function() { + instance.reset = function () { var direction = instance.direction; instance.passThrough = false; instance.currentTime = 0; @@ -1101,62 +1697,81 @@ instance.remaining = instance.loop; children = instance.children; childrenLength = children.length; - for (var i = childrenLength; i--;) { instance.children[i].reset(); } - if (instance.reversed && instance.loop !== true || (direction === 'alternate' && instance.loop === 1)) { instance.remaining++; } + + for (var i = childrenLength; i--;) { + instance.children[i].reset(); + } + + if (instance.reversed && instance.loop !== true || direction === 'alternate' && instance.loop === 1) { + instance.remaining++; + } + setAnimationsProgress(instance.reversed ? instance.duration : 0); - }; + }; // Set Value helper - // Set Value helper - instance.set = function(targets, properties) { + instance.set = function (targets, properties) { setTargetsValue(targets, properties); return instance; }; - instance.tick = function(t) { + instance.tick = function (t) { now = t; - if (!startTime) { startTime = now; } + + if (!startTime) { + startTime = now; + } + setInstanceProgress((now + (lastTime - startTime)) * anime.speed); }; - instance.seek = function(time) { + instance.seek = function (time) { setInstanceProgress(adjustTime(time)); }; - instance.pause = function() { + instance.pause = function () { instance.paused = true; resetTime(); }; - instance.play = function() { - if (!instance.paused) { return; } - if (instance.completed) { instance.reset(); } + instance.play = function () { + if (!instance.paused) { + return; + } + + if (instance.completed) { + instance.reset(); + } + instance.paused = false; activeInstances.push(instance); resetTime(); - if (!raf) { engine(); } + + if (!raf) { + engine(); + } }; - instance.reverse = function() { + instance.reverse = function () { toggleInstanceDirection(); instance.completed = instance.reversed ? false : true; resetTime(); }; - instance.restart = function() { + instance.restart = function () { instance.reset(); instance.play(); }; instance.reset(); - if (instance.autoplay) { instance.play(); } + if (instance.autoplay) { + instance.play(); + } return instance; + } // Remove targets from animation - } - - // Remove targets from animation function removeTargetsFromAnimations(targetsArray, animations) { for (var a = animations.length; a--;) { @@ -1168,26 +1783,32 @@ function removeTargets(targets) { var targetsArray = parseTargets(targets); + for (var i = activeInstances.length; i--;) { var instance = activeInstances[i]; var animations = instance.animations; var children = instance.children; removeTargetsFromAnimations(targetsArray, animations); + for (var c = children.length; c--;) { var child = children[c]; var childAnimations = child.animations; removeTargetsFromAnimations(targetsArray, childAnimations); - if (!childAnimations.length && !child.children.length) { children.splice(c, 1); } + + if (!childAnimations.length && !child.children.length) { + children.splice(c, 1); + } + } + + if (!animations.length && !children.length) { + instance.pause(); } - if (!animations.length && !children.length) { instance.pause(); } } - } + } // Stagger helpers - // Stagger helpers function stagger(val, params) { - if ( params === void 0 ) params = {}; - + if (params === void 0) params = {}; var direction = params.direction || 'normal'; var easing = params.easing ? parseEasings(params.easing) : null; var grid = params.grid; @@ -1204,48 +1825,85 @@ var values = []; var maxValue = 0; return function (el, i, t) { - if (fromFirst) { fromIndex = 0; } - if (fromCenter) { fromIndex = (t - 1) / 2; } - if (fromLast) { fromIndex = t - 1; } + if (fromFirst) { + fromIndex = 0; + } + + if (fromCenter) { + fromIndex = (t - 1) / 2; + } + + if (fromLast) { + fromIndex = t - 1; + } + if (!values.length) { for (var index = 0; index < t; index++) { if (!grid) { values.push(Math.abs(fromIndex - index)); } else { - var fromX = !fromCenter ? fromIndex%grid[0] : (grid[0]-1)/2; - var fromY = !fromCenter ? Math.floor(fromIndex/grid[0]) : (grid[1]-1)/2; - var toX = index%grid[0]; - var toY = Math.floor(index/grid[0]); + var fromX = !fromCenter ? fromIndex % grid[0] : (grid[0] - 1) / 2; + var fromY = !fromCenter ? Math.floor(fromIndex / grid[0]) : (grid[1] - 1) / 2; + var toX = index % grid[0]; + var toY = Math.floor(index / grid[0]); var distanceX = fromX - toX; var distanceY = fromY - toY; var value = Math.sqrt(distanceX * distanceX + distanceY * distanceY); - if (axis === 'x') { value = -distanceX; } - if (axis === 'y') { value = -distanceY; } + + if (axis === 'x') { + value = -distanceX; + } + + if (axis === 'y') { + value = -distanceY; + } + values.push(value); } + maxValue = Math.max.apply(Math, values); } - if (easing) { values = values.map(function (val) { return easing(val / maxValue) * maxValue; }); } - if (direction === 'reverse') { values = values.map(function (val) { return axis ? (val < 0) ? val * -1 : -val : Math.abs(maxValue - val); }); } + + if (easing) { + values = values.map(function (val) { + return easing(val / maxValue) * maxValue; + }); + } + + if (direction === 'reverse') { + values = values.map(function (val) { + return axis ? val < 0 ? val * -1 : -val : Math.abs(maxValue - val); + }); + } } + var spacing = isRange ? (val2 - val1) / maxValue : val1; - return start + (spacing * (Math.round(values[i] * 100) / 100)) + unit; - } - } + return start + spacing * (Math.round(values[i] * 100) / 100) + unit; + }; + } // Timeline - // Timeline function timeline(params) { - if ( params === void 0 ) params = {}; - + if (params === void 0) params = {}; var tl = anime(params); tl.duration = 0; - tl.add = function(instanceParams, timelineOffset) { + + tl.add = function (instanceParams, timelineOffset) { var tlIndex = activeInstances.indexOf(tl); var children = tl.children; - if (tlIndex > -1) { activeInstances.splice(tlIndex, 1); } - function passThrough(ins) { ins.passThrough = true; } - for (var i = 0; i < children.length; i++) { passThrough(children[i]); } + + if (tlIndex > -1) { + activeInstances.splice(tlIndex, 1); + } + + function passThrough(ins) { + ins.passThrough = true; + } + + for (var i = 0; i < children.length; i++) { + passThrough(children[i]); + } + var insParams = mergeObjects(instanceParams, replaceObjectProps(defaultTweenSettings, params)); insParams.targets = insParams.targets || params.targets; var tlDuration = tl.duration; @@ -1263,9 +1921,14 @@ tl.duration = timings.duration; tl.seek(0); tl.reset(); - if (tl.autoplay) { tl.play(); } + + if (tl.autoplay) { + tl.play(); + } + return tl; }; + return tl; } @@ -1282,13 +1945,14 @@ anime.timeline = timeline; anime.easing = parseEasings; anime.penner = penner; - anime.random = function (min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; }; - - const NAME_SPACE = 'http://www.w3.org/2000/svg'; - let did = 1; + anime.random = function (min, max) { + return Math.floor(Math.random() * (max - min + 1)) + min; + }; - const svgDefaultAttrs = { + var NAME_SPACE = 'http://www.w3.org/2000/svg'; + var did = 1; + var svgDefaultAttrs = { version: '1.1', baseProfile: 'full', xmlns: 'http://www.w3.org/2000/svg', @@ -1296,140 +1960,203 @@ 'xmlns:ev': 'http://www.w3.org/2001/xml-events' }; - function completeSVGAttrs (el, attrs) { - if (!attrs) return - for (const key in svgDefaultAttrs) { + function completeSVGAttrs(el, attrs) { + if (!attrs) return; + + for (var key in svgDefaultAttrs) { if (el && attrs[key] === undefined && el.hasAttribute(key)) { attrs[key] = el.getAttribute(key); } + if (attrs[key] === undefined || attrs[key] === null || attrs[key] === '') { attrs[key] = svgDefaultAttrs[key]; } } } - function createElNS (tag, attrs = {}) { - const el = document.createElementNS(NAME_SPACE, tag); - for (const key in attrs) { + function createElNS(tag) { + var attrs = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var el = document.createElementNS(NAME_SPACE, tag); + + for (var key in attrs) { el.setAttribute(key, attrs[key]); } - return el + + return el; } - function createMatrix (a = 1, b = 0, c = 0, d = 1, e = 0, f = 0) { - return { a, b, c, d, e, f } + function createMatrix() { + var a = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1; + var b = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var c = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var d = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1; + var e = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0; + var f = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0; + return { + a: a, + b: b, + c: c, + d: d, + e: e, + f: f + }; } - function getMatrix (el) { - const transformString = el.hasAttribute('transform'); - if (!transformString || transformString.indexOf('matrix') < 0) return createMatrix() - const values = transformString.split(','); - return createMatrix(...values) + function getMatrix(el) { + var transformString = el.hasAttribute('transform'); + if (!transformString || transformString.indexOf('matrix') < 0) return createMatrix(); + var values = transformString.split(','); + return createMatrix.apply(void 0, _toConsumableArray(values)); } - function circle (cx, cy, radius, attrs = {}) { + function circle(cx, cy, radius) { + var attrs = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; attrs.cx = cx; attrs.cy = cy; attrs.r = radius; - return createElNS('circle', attrs) - } - - function dropShadow (rootEl, el, attrs = {}) { - const id = `drop-shadow-${did++}`; - const defs = createElNS('defs'); - const filter = createElNS('filter', { id, filterUnits: 'userSpaceOnUse' }); - const blur = createElNS('feGaussianBlur', { in: 'SourceAlpha', stdDeviation: attrs.blurStdDeviation || 0 }); - const offset = createElNS('feOffset', { dx: attrs.offsetDx || 0, dy: attrs.offsetDy || 0 }); - const transfer = createElNS('feComponentTransfer'); - const funcA = createElNS('feFuncA', { type: 'linear', slope: 0.5 }); - transfer.appendChild(funcA); - const merge = createElNS('feMerge'); - const mergeNodeA = createElNS('feMergeNode'); - const mergeNodeB = createElNS('feMergeNode', { in: 'SourceGraphic' }); + return createElNS('circle', attrs); + } + function dropShadow(rootEl, el, offsetX, offsetY, blur) { + var opacity = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 1; + var id = "drop-shadow-".concat(did++); + var defs = createElNS('defs'); + var filter = createElNS('filter', { + id: id, + filterUnits: 'userSpaceOnUse' + }); + var gBlur = createElNS('feGaussianBlur', { + in: 'SourceAlpha', + stdDeviation: blur + }); + var offset = createElNS('feOffset', { + dx: offsetX, + dy: offsetY + }); + var merge = createElNS('feMerge'); + var mergeNodeA = createElNS('feMergeNode'); + var mergeNodeB = createElNS('feMergeNode', { + in: 'SourceGraphic' + }); merge.appendChild(mergeNodeA); merge.appendChild(mergeNodeB); - filter.appendChild(blur); + filter.appendChild(gBlur); filter.appendChild(offset); - filter.appendChild(transfer); + + if (opacity !== 1) { + var transfer = createElNS('feComponentTransfer'); + var funcA = createElNS('feFuncA', { + type: 'linear', + slope: opacity + }); + transfer.appendChild(funcA); + filter.appendChild(transfer); + } + filter.appendChild(merge); defs.appendChild(filter); rootEl.appendChild(defs); - el.setAttribute('filter', `url(#${id})`); + el.setAttribute('filter', "url(#".concat(id, ")")); } + function g() { + var children = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; + var attrs = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var el = createElNS('g', attrs); + + var _iterator = _createForOfIteratorHelper(children), + _step; - function g (children = [], attrs = {}) { - const el = createElNS('g', attrs); - for (const child of children) { - el.appendChild(child); + try { + for (_iterator.s(); !(_step = _iterator.n()).done;) { + var child = _step.value; + el.appendChild(child); + } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); } - return el - } - function image (href, attrs = {}) { + return el; + } + function image(href) { + var attrs = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; attrs.href = href; - return createElNS('image', attrs) + return createElNS('image', attrs); } - - function path (d, attrs = {}) { + function path(d) { + var attrs = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; attrs.d = d; - return createElNS('path', attrs) - } - - function rotate (el, r, cx = 0, cy = 0) { - const cos = Math.cos(r); - const sin = Math.sin(r); - - const { a, b, c, d, e, f } = getMatrix(el); - - const na = a * cos - b * sin; - const nb = b * cos + a * sin; - const nc = c * cos - d * sin; - const nd = d * cos + c * sin; - const ne = e * cos - f * sin + cy * sin - cx * cos + cx; - const nf = f * cos + e * sin - cx * sin - cy * cos + cy; - - el.setAttribute('transform', `matrix(${na},${nb},${nc},${nd},${ne},${nf})`); - } - - function svg (attrs = {}) { + return createElNS('path', attrs); + } + function rotate(el, r) { + var cx = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var cy = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + var cos = Math.cos(r); + var sin = Math.sin(r); + + var _getMatrix = getMatrix(el), + a = _getMatrix.a, + b = _getMatrix.b, + c = _getMatrix.c, + d = _getMatrix.d, + e = _getMatrix.e, + f = _getMatrix.f; + + var na = a * cos - b * sin; + var nb = b * cos + a * sin; + var nc = c * cos - d * sin; + var nd = d * cos + c * sin; + var ne = e * cos - f * sin + cy * sin - cx * cos + cx; + var nf = f * cos + e * sin - cx * sin - cy * cos + cy; + el.setAttribute('transform', "matrix(".concat(na, ",").concat(nb, ",").concat(nc, ",").concat(nd, ",").concat(ne, ",").concat(nf, ")")); + } + function svg() { + var attrs = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; completeSVGAttrs(null, attrs); - return createElNS('svg', attrs) + return createElNS('svg', attrs); } - - function text (text, attrs = {}) { - const el = createElNS('text', attrs); + function text(text) { + var attrs = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var el = createElNS('text', attrs); el.textContent = text; - return el + return el; } + function translate(el, x) { + var y = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : x; - function translate (el, x, y = x) { - const { a, b, c, d, e, f } = getMatrix(el); - el.setAttribute('transform', `matrix(${a},${b},${c},${d},${e + x},${f + y})`); - } + var _getMatrix2 = getMatrix(el), + a = _getMatrix2.a, + b = _getMatrix2.b, + c = _getMatrix2.c, + d = _getMatrix2.d, + e = _getMatrix2.e, + f = _getMatrix2.f; - function useSVG (el, attrs = {}) { - if (el.tagName !== 'svg') return + el.setAttribute('transform', "matrix(".concat(a, ",").concat(b, ",").concat(c, ",").concat(d, ",").concat(e + x, ",").concat(f + y, ")")); + } + function useSVG(el) { + var attrs = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + if (el.tagName !== 'svg') return; completeSVGAttrs(el, attrs); - for (const key in attrs) { + + for (var key in attrs) { el.setAttribute(key, attrs[key]); } } - function degreeToRadians (degree) { - return (degree * Math.PI) / 180 + function degreeToRadians(degree) { + return degree * Math.PI / 180; } - - function polarToCartesian (centerX, centerY, radius, angleInDegrees) { - const angleInRadians = degreeToRadians(angleInDegrees - 90); + function polarToCartesian(centerX, centerY, radius, angleInDegrees) { + var angleInRadians = degreeToRadians(angleInDegrees - 90); return { x: centerX + radius * Math.cos(angleInRadians), y: centerY + radius * Math.sin(angleInRadians) - } + }; } - const baseFontSize = 16; - - const themes = { + var baseFontSize = 16; + var themes = { default: { border: 'red', prize: 'gold', @@ -1456,9 +2183,13 @@ } }; - class Wheel { - constructor (option = {}) { - this.option = { + var Wheel = /*#__PURE__*/function () { + function Wheel() { + var option = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + + _classCallCheck(this, Wheel); + + this.option = _objectSpread2({ pos: [0, 0], radius: 100, buttonWidth: 50, @@ -1470,15 +2201,14 @@ turn: 4, clockwise: true, draw: true, - theme: 'default', - ...option - }; + theme: 'default' + }, option); + if (!this.option.el) throw new Error('el is undefined'); + if (!this.option.data) throw new Error('data is undefined'); + var len = this.option.data.length; - if (!this.option.el) throw new Error('el is undefined') - if (!this.option.data) throw new Error('data is undefined') - const len = this.option.data.length; if (len < 3 || len > 12) { - throw new Error('data.length must between 3 and 12') + throw new Error('data.length must between 3 and 12'); } this._count = 0; @@ -1492,318 +2222,340 @@ if (this.option.draw) this.draw(); } - _checkPrize () { - const data = this.option.data; - for (const i in data) { - const d = data[i]; - if (typeof d === 'string') { - data[i] = { - text: d, - chance: 1 - }; - } else { - data[i] = { - ...data[i], - text: d.text || i, - chance: d.chance > 0 ? d.chance : 1 - }; - } + _createClass(Wheel, [{ + key: "_checkPrize", + value: function _checkPrize() { + var data = this.option.data; - this._weight.push(Number(data[i].chance)); - this._weightSum += Number(data[i].chance); - } - } + for (var i in data) { + var d = data[i]; - draw () { - const opt = this.option; + if (typeof d === 'string') { + data[i] = { + text: d, + chance: 1 + }; + } else { + data[i] = _objectSpread2(_objectSpread2({}, data[i]), {}, { + text: d.text || i, + chance: d.chance > 0 ? d.chance : 1 + }); + } - this._center = opt.pos.map(p => p + opt.radius); + this._weight.push(Number(data[i].chance)); - const svgAttrs = { - width: opt.radius * 2, - height: opt.radius * 2 - }; - if (opt.el.tagName !== 'svg') { - this._svg = svg(svgAttrs); - opt.el.appendChild(this._svg); - } else { - this._svg = opt.el; - useSVG(opt.el, svgAttrs); + this._weightSum += Number(data[i].chance); + } } + }, { + key: "draw", + value: function draw() { + var opt = this.option; + this._center = opt.pos.map(function (p) { + return p + opt.radius; + }); + var svgAttrs = { + width: opt.radius * 2, + height: opt.radius * 2 + }; + + if (opt.el.tagName !== 'svg') { + this._svg = svg(svgAttrs); + opt.el.appendChild(this._svg); + } else { + this._svg = opt.el; + useSVG(opt.el, svgAttrs); + } - this._deg = 360 / opt.data.length; + this._deg = 360 / opt.data.length; + if (opt.image) this._drawResource(); - if (opt.image) this._drawResource(); - this._drawDefault(); + this._drawDefault(); - this._animeFunc(); - } + this._animeFunc(); + } + }, { + key: "_drawDefault", + value: function _drawDefault() { + if (this._turntable && this._button) return; + var opt = this.option; + var theme = themes[opt.theme] || themes.default; + opt.color = _objectSpread2(_objectSpread2({}, theme), opt.color); + + if (!opt.inRadius) { + opt.inRadius = getInnerRadius(opt.radius); + } else if (opt.inRadius > opt.radius) { + opt.inRadius = opt.radius; + } - _drawDefault () { - if (this._turntable && this._button) return + if (!this._turntable) this._drawTurntable(); + if (!this._button) this._drawButton(); + } + }, { + key: "_drawResource", + value: function _drawResource() { + var opt = this.option; + var res = opt.image; + + if (_typeof(res) === 'object' && Object.keys(res).length > 0) { + if (res.turntable && typeof res.turntable === 'string') { + this._turntable = image(res.turntable, { + width: opt.radius * 2, + height: opt.radius * 2, + x: opt.pos[0], + y: opt.pos[1] + }); + + this._svg.appendChild(this._turntable); + } - const opt = this.option; - const theme = themes[opt.theme] || themes.default; - opt.color = { - ...theme, - ...opt.color - }; - if (!opt.inRadius) { - opt.inRadius = getInnerRadius(opt.radius); - } else if (opt.inRadius > opt.radius) { - opt.inRadius = opt.radius; - } - - if (!this._turntable) this._drawTurntable(); - if (!this._button) this._drawButton(); - } - - _drawResource () { - const opt = this.option; - const res = opt.image; - if (typeof res === 'object' && Object.keys(res).length > 0) { - if (res.turntable && typeof res.turntable === 'string') { - this._turntable = image(res.turntable, { - width: opt.radius * 2, - height: opt.radius * 2, - x: opt.pos[0], - y: opt.pos[1] - }); - this._svg.appendChild(this._turntable); - } - if (res.button && typeof res.button === 'string') { - if (!res.offset || typeof res.offset !== 'number') res.offset = 0; - const size = [50, 50]; - const buttonHeight = (size[1] * opt.buttonWidth) / size[0]; - this._button = image(res.button, { - width: opt.buttonWidth, - height: buttonHeight, - x: this._center[0] - opt.buttonWidth / 2, - y: this._center[1] + res.offset - buttonHeight / 2 - }); - this._svg.appendChild(this._button); + if (res.button && typeof res.button === 'string') { + if (!res.offset || typeof res.offset !== 'number') res.offset = 0; + var size = [50, 50]; + var buttonHeight = size[1] * opt.buttonWidth / size[0]; + this._button = image(res.button, { + width: opt.buttonWidth, + height: buttonHeight, + x: this._center[0] - opt.buttonWidth / 2, + y: this._center[1] + res.offset - buttonHeight / 2 + }); + + this._svg.appendChild(this._button); + } } } - } + }, { + key: "_drawTurntable", + value: function _drawTurntable() { + if (this._turntable) return; + var opt = this.option; - _drawTurntable () { - if (this._turntable) return - - const opt = this.option; - this._svg.appendChild( - circle(this._center[0], this._center[1], opt.radius, { + this._svg.appendChild(circle(this._center[0], this._center[1], opt.radius, { fill: opt.color.border - }) - ); - this._svg.appendChild( - circle(this._center[0], this._center[1], opt.inRadius, { + })); + + this._svg.appendChild(circle(this._center[0], this._center[1], opt.inRadius, { fill: opt.color.prize - }) - ); - - this._turntable = g(); - this._svg.appendChild(this._turntable); - for (const d of opt.data) { - const [pathD, dLen] = describeArc( - this._center[0], - this._center[1], - opt.inRadius, - -this._deg / 2, - this._deg / 2 - ); - - const pie = path(pathD, { - fill: d.color || opt.color.prize, - stroke: opt.color.line, - strokeWidth: 2 - }); + })); + + this._turntable = g(); + + this._svg.appendChild(this._turntable); + + var _iterator = _createForOfIteratorHelper(opt.data), + _step; + + try { + for (_iterator.s(); !(_step = _iterator.n()).done;) { + var d = _step.value; + + var _describeArc = describeArc(this._center[0], this._center[1], opt.inRadius, -this._deg / 2, this._deg / 2), + _describeArc2 = _slicedToArray(_describeArc, 2), + pathD = _describeArc2[0], + dLen = _describeArc2[1]; + + var pie = path(pathD, { + fill: d.color || opt.color.prize, + stroke: opt.color.line, + strokeWidth: 2 + }); + var fontSize = d.fontSize || opt.fontSize; + + if (!fontSize) { + var textSum = 0; + + for (var i = 0; i < d.text.length; ++i) { + if (d.text[i].match(/\w/)) { + textSum += 1; + } else textSum += 2; + } - let fontSize = d.fontSize || opt.fontSize; - if (!fontSize) { - let textSum = 0; - for (let i = 0; i < d.text.length; ++i) { - if (d.text[i].match(/\w/)) { - textSum += 1; - } else textSum += 2; + fontSize = baseFontSize * textSum / 2 > dLen * opt.textBottomPercentage ? dLen * opt.textBottomPercentage / textSum * 2 : baseFontSize; + } + + var text$1 = text(d.text, { + x: this._center[0], + y: opt.pos[1] + opt.radius - opt.inRadius * opt.textBottomPercentage, + fontSize: fontSize, + fill: d.fontColor || opt.color.prizeFont + }); + var g$1 = g([pie, text$1]); + rotate(g$1, degreeToRadians(this._deg * opt.data.indexOf(d)), this._center[0], this._center[1]); + + this._turntable.appendChild(g$1); + + translate(text$1, -text$1.getComputedTextLength() / 2, 0); } - fontSize = - (baseFontSize * textSum) / 2 > dLen * opt.textBottomPercentage - ? ((dLen * opt.textBottomPercentage) / textSum) * 2 - : baseFontSize; + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); } - const text$1 = text(d.text, { - x: this._center[0], - y: - opt.pos[1] + - opt.radius - - opt.inRadius * opt.textBottomPercentage, - fontSize, - fill: d.fontColor || opt.color.prizeFont - }); - const g$1 = g([pie, text$1]); - rotate( - g$1, - degreeToRadians(this._deg * opt.data.indexOf(d)), - this._center[0], - this._center[1] - ); - this._turntable.appendChild(g$1); - translate(text$1, -text$1.getComputedTextLength() / 2, 0); } - } + }, { + key: "_drawButton", + value: function _drawButton() { + if (this._button) return; + var opt = this.option; + if (opt.button && typeof opt.button === 'string') return; + var r = opt.buttonWidth / 2; + var center = this._center; + var deg = (180 - opt.buttonDeg) / 2; + + var _describeArc3 = describeArc(center[0], center[1], r, deg - 360, 360 - deg), + _describeArc4 = _slicedToArray(_describeArc3, 4), + pathArc = _describeArc4[0], + end = _describeArc4[3]; + + var top = [center[0], center[1] - r / Math.cos(degreeToRadians(deg))]; + var pathD = "".concat(pathArc, " L ").concat(top[0], " ").concat(top[1], " L ").concat(end.x, " ").concat(end.y, " L ").concat(center[0], " ").concat(center[1]); + var button = path(pathD, { + fill: opt.color.button + }); + dropShadow(this._svg, button, 0, 3, 3, 0.5); + var text$1 = null; - _drawButton () { - if (this._button) return - - const opt = this.option; - if (opt.button && typeof opt.button === 'string') return - - const r = opt.buttonWidth / 2; - const center = this._center; - const deg = (180 - opt.buttonDeg) / 2; - const [pathArc, , , end] = describeArc( - center[0], - center[1], - r, - deg - 360, - 360 - deg - ); - const top = [center[0], center[1] - r / Math.cos(degreeToRadians(deg))]; - const pathD = `${pathArc} L ${top[0]} ${top[1]} L ${end.x} ${end.y} L ${center[0]} ${center[1]}`; - const button = path(pathD, { fill: opt.color.button }); - dropShadow(this._svg, button, { - blurStdDeviation: 3, - offsetDy: 3 - }); + if (opt.buttonText !== '') { + var maxLen = r * 2 * 0.8; + var fontSize = opt.buttonFontSize; + + if (!fontSize) { + var textSum = 0; + + for (var i = 0; i < opt.buttonText.length; ++i) { + if (opt.buttonText[i].match(/\w/)) { + textSum += 1; + } else textSum += 2; + } - let text$1 = null; - if (opt.buttonText !== '') { - const maxLen = r * 2 * 0.8; - let fontSize = opt.buttonFontSize; - if (!fontSize) { - let textSum = 0; - for (let i = 0; i < opt.buttonText.length; ++i) { - if (opt.buttonText[i].match(/\w/)) { - textSum += 1; - } else textSum += 2; + fontSize = baseFontSize * textSum / 2 > maxLen ? maxLen / textSum * 2 : baseFontSize; } - fontSize = - (baseFontSize * textSum) / 2 > maxLen - ? (maxLen / textSum) * 2 - : baseFontSize; - } - text$1 = text(opt.buttonText, { + + text$1 = text(opt.buttonText, { x: center[0], y: center[1], - fontSize, + fontSize: fontSize, fill: opt.color.buttonFont }); - } + } - this._button = g([button, text$1]); - this._svg.appendChild(this._button); - translate(text$1, -text$1.getComputedTextLength() / 2, 0); - } + this._button = g([button, text$1]); - _animeFunc () { - const opt = this.option; + this._svg.appendChild(this._button); - this._turntable.style['transform-origin'] = 'center'; + translate(text$1, -text$1.getComputedTextLength() / 2, 0); + } + }, { + key: "_animeFunc", + value: function _animeFunc() { + var _this = this; + + var opt = this.option; + this._turntable.style['transform-origin'] = 'center'; + this._button.style.cursor = 'pointer'; + this._button.style['transform-origin'] = 'center'; + + this._button.addEventListener('mouseover', function () { + if (opt.onButtonHover && typeof opt.onButtonHover === 'function') { + opt.onButtonHover(anime, _this._button); + return; + } - this._button.style.cursor = 'pointer'; - this._button.style['transform-origin'] = 'center'; - this._button.addEventListener('mouseover', () => { - if (opt.onButtonHover && typeof opt.onButtonHover === 'function') { - opt.onButtonHover(anime, this._button); - return - } - anime({ - targets: this._button, - scale: 1.2, - duration: 500 - }); - }); - this._button.addEventListener('mouseout', () => { - anime({ - targets: this._button, - scale: 1, - duration: 500 + anime({ + targets: _this._button, + scale: 1.2, + duration: 500 + }); }); - }); - this._button.addEventListener('click', () => { - this._run(); - }); - } - _run () { - if (this._running) return + this._button.addEventListener('mouseout', function () { + anime({ + targets: _this._button, + scale: 1, + duration: 500 + }); + }); - const opt = this.option; - if (opt.limit > 0 && this._count >= opt.limit) { - opt.onFail && typeof opt.onFail === 'function' && opt.onFail(); - return + this._button.addEventListener('click', function () { + _this._run(); + }); } + }, { + key: "_run", + value: function _run() { + var _this2 = this; - const runAnime = pie => { - if (this._rotation > 0) { - const revision = 360 - (this._rotation % 360); - this._rotation += revision; + if (this._running) return; + var opt = this.option; + + if (opt.limit > 0 && this._count >= opt.limit) { + opt.onFail && typeof opt.onFail === 'function' && opt.onFail(); + return; } - this._rotation += getRotation(pie, this._deg, opt.turn); - anime({ - targets: this._turntable, - rotate: opt.clockwise - ? this._rotation + 'deg' - : '-' + this._rotation + 'deg', - duration: opt.duration, - begin: () => { - this._running = true; - }, - complete: () => { - this._running = false; - ++this._count; - if (opt.onSuccess && typeof opt.onSuccess === 'function') { - const d = opt.clockwise - ? opt.data[(opt.data.length - pie) % opt.data.length] - : opt.data[pie]; - opt.onSuccess(d); - } + + var runAnime = function runAnime(pie) { + if (_this2._rotation > 0) { + var revision = 360 - _this2._rotation % 360; + _this2._rotation += revision; } - }); - }; - const random = Math.random() * this._weightSum; - let randomWeight = 0; - let pie = 0; - for (const i in this._weight) { - randomWeight += this._weight[i]; - if (randomWeight > random) { - pie = i; - runAnime(pie); - break + _this2._rotation += getRotation(pie, _this2._deg, opt.turn); + anime({ + targets: _this2._turntable, + rotate: opt.clockwise ? _this2._rotation + 'deg' : '-' + _this2._rotation + 'deg', + duration: opt.duration, + begin: function begin() { + _this2._running = true; + }, + complete: function complete() { + _this2._running = false; + ++_this2._count; + + if (opt.onSuccess && typeof opt.onSuccess === 'function') { + var d = opt.clockwise ? opt.data[(opt.data.length - pie) % opt.data.length] : opt.data[pie]; + opt.onSuccess(d); + } + } + }); + }; + + var random = Math.random() * this._weightSum; + + var randomWeight = 0; + var pie = 0; + + for (var i in this._weight) { + randomWeight += this._weight[i]; + + if (randomWeight > random) { + pie = i; + runAnime(pie); + break; + } } } - } - } + }]); - function getInnerRadius (radius) { - if (radius < 50) return radius - if (radius < 100) return radius - 10 - return Math.round(radius / 10) * 9 - } + return Wheel; + }(); - function describeArc (x, y, radius, startAngle, endAngle) { - const start = polarToCartesian(x, y, radius, endAngle); - const end = polarToCartesian(x, y, radius, startAngle); + function getInnerRadius(radius) { + if (radius < 50) return radius; + if (radius < 100) return radius - 10; + return Math.round(radius / 10) * 9; + } - const largeArcFlag = endAngle - startAngle <= 180 ? 0 : 1; - const d = `M ${start.x} ${start.y} A ${radius} ${radius} 0 ${largeArcFlag} 0 ${end.x} ${end.y} L ${x} ${y} L ${start.x} ${start.y}`; - const l = start.x - end.x; - return [d, l, start, end] + function describeArc(x, y, radius, startAngle, endAngle) { + var start = polarToCartesian(x, y, radius, endAngle); + var end = polarToCartesian(x, y, radius, startAngle); + var largeArcFlag = endAngle - startAngle <= 180 ? 0 : 1; + var d = "M ".concat(start.x, " ").concat(start.y, " A ").concat(radius, " ").concat(radius, " 0 ").concat(largeArcFlag, " 0 ").concat(end.x, " ").concat(end.y, " L ").concat(x, " ").concat(y, " L ").concat(start.x, " ").concat(start.y); + var l = start.x - end.x; + return [d, l, start, end]; } - function getRotation (i, deg, minTurn) { - return minTurn * 360 + i * deg + function getRotation(i, deg, minTurn) { + return minTurn * 360 + i * deg; } return Wheel; diff --git a/dist/lottery-wheel.min.js b/dist/lottery-wheel.min.js index c299ff4..9198c19 100644 --- a/dist/lottery-wheel.min.js +++ b/dist/lottery-wheel.min.js @@ -1 +1 @@ -!function(t,n){"object"==typeof exports&&"undefined"!=typeof module?module.exports=n():"function"==typeof define&&define.amd?define(n):(t=t||self).Wheel=n()}(this,(function(){"use strict";var t={update:null,begin:null,loopBegin:null,changeBegin:null,change:null,changeComplete:null,loopComplete:null,complete:null,loop:1,direction:"normal",autoplay:!0,timelineOffset:0},n={duration:1e3,delay:0,endDelay:0,easing:"easeOutElastic(1, .5)",round:0},e=["translateX","translateY","translateZ","rotate","rotateX","rotateY","rotateZ","scale","scaleX","scaleY","scaleZ","skew","skewX","skewY","perspective","matrix","matrix3d"],r={CSS:{},springs:{}};function i(t,n,e){return Math.min(Math.max(t,n),e)}function o(t,n){return t.indexOf(n)>-1}function a(t,n){return t.apply(null,n)}var u={arr:function(t){return Array.isArray(t)},obj:function(t){return o(Object.prototype.toString.call(t),"Object")},pth:function(t){return u.obj(t)&&t.hasOwnProperty("totalLength")},svg:function(t){return t instanceof SVGElement},inp:function(t){return t instanceof HTMLInputElement},dom:function(t){return t.nodeType||u.svg(t)},str:function(t){return"string"==typeof t},fnc:function(t){return"function"==typeof t},und:function(t){return void 0===t},hex:function(t){return/(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(t)},rgb:function(t){return/^rgb/.test(t)},hsl:function(t){return/^hsl/.test(t)},col:function(t){return u.hex(t)||u.rgb(t)||u.hsl(t)},key:function(e){return!t.hasOwnProperty(e)&&!n.hasOwnProperty(e)&&"targets"!==e&&"keyframes"!==e}};function s(t){var n=/\(([^)]+)\)/.exec(t);return n?n[1].split(",").map((function(t){return parseFloat(t)})):[]}function c(t,n){var e=s(t),o=i(u.und(e[0])?1:e[0],.1,100),a=i(u.und(e[1])?100:e[1],.1,100),c=i(u.und(e[2])?10:e[2],.1,100),f=i(u.und(e[3])?0:e[3],.1,100),l=Math.sqrt(a/o),d=c/(2*Math.sqrt(a*o)),h=d<1?l*Math.sqrt(1-d*d):0,p=d<1?(d*l-f)/h:-f+l;function g(t){var e=n?n*t/1e3:t;return e=d<1?Math.exp(-e*d*l)*(1*Math.cos(h*e)+p*Math.sin(h*e)):(1+p*e)*Math.exp(-e*l),0===t||1===t?t:1-e}return n?g:function(){var n=r.springs[t];if(n)return n;for(var e=0,i=0;;)if(1===g(e+=1/6)){if(++i>=16)break}else i=0;var o=e*(1/6)*1e3;return r.springs[t]=o,o}}function f(t){return void 0===t&&(t=10),function(n){return Math.ceil(i(n,1e-6,1)*t)*(1/t)}}var l,d,h=function(){function t(t,n){return 1-3*n+3*t}function n(t,n){return 3*n-6*t}function e(t){return 3*t}function r(r,i,o){return((t(i,o)*r+n(i,o))*r+e(i))*r}function i(r,i,o){return 3*t(i,o)*r*r+2*n(i,o)*r+e(i)}return function(t,n,e,o){if(0<=t&&t<=1&&0<=e&&e<=1){var a=new Float32Array(11);if(t!==n||e!==o)for(var u=0;u<11;++u)a[u]=r(.1*u,t,e);return function(i){return t===n&&e===o||0===i||1===i?i:r(s(i),n,o)}}function s(n){for(var o=0,u=1;10!==u&&a[u]<=n;++u)o+=.1;--u;var s=o+.1*((n-a[u])/(a[u+1]-a[u])),c=i(s,t,e);return c>=.001?function(t,n,e,o){for(var a=0;a<4;++a){var u=i(n,e,o);if(0===u)return n;n-=(r(n,e,o)-t)/u}return n}(n,s,t,e):0===c?s:function(t,n,e,i,o){var a,u,s=0;do{(a=r(u=n+(e-n)/2,i,o)-t)>0?e=u:n=u}while(Math.abs(a)>1e-7&&++s<10);return u}(n,o,o+.1,t,e)}}}(),p=(l={linear:function(){return function(t){return t}}},d={Sine:function(){return function(t){return 1-Math.cos(t*Math.PI/2)}},Circ:function(){return function(t){return 1-Math.sqrt(1-t*t)}},Back:function(){return function(t){return t*t*(3*t-2)}},Bounce:function(){return function(t){for(var n,e=4;t<((n=Math.pow(2,--e))-1)/11;);return 1/Math.pow(4,3-e)-7.5625*Math.pow((3*n-2)/22-t,2)}},Elastic:function(t,n){void 0===t&&(t=1),void 0===n&&(n=.5);var e=i(t,1,10),r=i(n,.1,2);return function(t){return 0===t||1===t?t:-e*Math.pow(2,10*(t-1))*Math.sin((t-1-r/(2*Math.PI)*Math.asin(1/e))*(2*Math.PI)/r)}}},["Quad","Cubic","Quart","Quint","Expo"].forEach((function(t,n){d[t]=function(){return function(t){return Math.pow(t,n+2)}}})),Object.keys(d).forEach((function(t){var n=d[t];l["easeIn"+t]=n,l["easeOut"+t]=function(t,e){return function(r){return 1-n(t,e)(1-r)}},l["easeInOut"+t]=function(t,e){return function(r){return r<.5?n(t,e)(2*r)/2:1-n(t,e)(-2*r+2)/2}}})),l);function g(t,n){if(u.fnc(t))return t;var e=t.split("(")[0],r=p[e],i=s(t);switch(e){case"spring":return c(t,n);case"cubicBezier":return a(h,i);case"steps":return a(f,i);default:return a(r,i)}}function v(t){try{return document.querySelectorAll(t)}catch(t){return}}function m(t,n){for(var e=t.length,r=arguments.length>=2?arguments[1]:void 0,i=[],o=0;o1&&(e-=1),e<1/6?t+6*(n-t)*e:e<.5?n:e<2/3?t+(n-t)*(2/3-e)*6:t}if(0==a)n=e=r=u;else{var f=u<.5?u*(1+a):u+a-u*a,l=2*u-f;n=c(l,f,o+1/3),e=c(l,f,o),r=c(l,f,o-1/3)}return"rgba("+255*n+","+255*e+","+255*r+","+s+")"}(t):void 0;var n,e}function k(t){var n=/[+-]?\d*\.?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?(%|px|pt|em|rem|in|cm|mm|ex|ch|pc|vw|vh|vmin|vmax|deg|rad|turn)?$/.exec(t);if(n)return n[1]}function $(t,n){return u.fnc(t)?t(n.target,n.id,n.total):t}function B(t,n){return t.getAttribute(n)}function F(t,n,e){if(w([e,"deg","rad","turn"],k(n)))return n;var i=r.CSS[n+e];if(!u.und(i))return i;var o=document.createElement(t.tagName),a=t.parentNode&&t.parentNode!==document?t.parentNode:document.body;a.appendChild(o),o.style.position="absolute",o.style.width=100+e;var s=100/o.offsetWidth;a.removeChild(o);var c=s*parseFloat(n);return r.CSS[n+e]=c,c}function O(t,n,e){if(n in t.style){var r=n.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase(),i=t.style[n]||getComputedStyle(t).getPropertyValue(r)||"0";return e?F(t,i,e):i}}function P(t,n){return u.dom(t)&&!u.inp(t)&&(B(t,n)||u.svg(t)&&t[n])?"attribute":u.dom(t)&&w(e,n)?"transform":u.dom(t)&&"transform"!==n&&O(t,n)?"css":null!=t[n]?"object":void 0}function S(t){if(u.dom(t)){for(var n,e=t.style.transform||"",r=/(\w+)\(([^)]*)\)/g,i=new Map;n=r.exec(e);)i.set(n[1],n[2]);return i}}function D(t,n,e,r){var i=o(n,"scale")?1:0+function(t){return o(t,"translate")||"perspective"===t?"px":o(t,"rotate")||o(t,"skew")?"deg":void 0}(n),a=S(t).get(n)||i;return e&&(e.transforms.list.set(n,a),e.transforms.last=n),r?F(t,a,r):a}function T(t,n,e,r){switch(P(t,n)){case"transform":return D(t,n,r,e);case"css":return O(t,n,e);case"attribute":return B(t,n);default:return t[n]||0}}function A(t,n){var e=/^(\*=|\+=|-=)/.exec(t);if(!e)return t;var r=k(t)||0,i=parseFloat(n),o=parseFloat(t.replace(e[0],""));switch(e[0][0]){case"+":return i+o+r;case"-":return i-o+r;case"*":return i*o+r}}function E(t,n){if(u.col(t))return C(t);if(/\s/g.test(t))return t;var e=k(t),r=e?t.substr(0,t.length-e.length):t;return n?r+n:r}function L(t,n){return Math.sqrt(Math.pow(n.x-t.x,2)+Math.pow(n.y-t.y,2))}function N(t){for(var n,e=t.points,r=0,i=0;i0&&(r+=L(n,o)),n=o}return r}function I(t){if(t.getTotalLength)return t.getTotalLength();switch(t.tagName.toLowerCase()){case"circle":return function(t){return 2*Math.PI*B(t,"r")}(t);case"rect":return function(t){return 2*B(t,"width")+2*B(t,"height")}(t);case"line":return function(t){return L({x:B(t,"x1"),y:B(t,"y1")},{x:B(t,"x2"),y:B(t,"y2")})}(t);case"polyline":return N(t);case"polygon":return function(t){var n=t.points;return N(t)+L(n.getItem(n.numberOfItems-1),n.getItem(0))}(t)}}function z(t,n){var e=n||{},r=e.el||function(t){for(var n=t.parentNode;u.svg(n)&&u.svg(n.parentNode);)n=n.parentNode;return n}(t),i=r.getBoundingClientRect(),o=B(r,"viewBox"),a=i.width,s=i.height,c=e.viewBox||(o?o.split(" "):[0,0,a,s]);return{el:r,viewBox:c,x:c[0]/1,y:c[1]/1,w:a/c[2],h:s/c[3]}}function j(t,n){function e(e){void 0===e&&(e=0);var r=n+e>=1?n+e:0;return t.el.getPointAtLength(r)}var r=z(t.el,t.svg),i=e(),o=e(-1),a=e(1);switch(t.property){case"x":return(i.x-r.x)*r.w;case"y":return(i.y-r.y)*r.h;case"angle":return 180*Math.atan2(a.y-o.y,a.x-o.x)/Math.PI}}function R(t,n){var e=/[+-]?\d*\.?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/g,r=E(u.pth(t)?t.totalLength:t,n)+"";return{original:r,numbers:r.match(e)?r.match(e).map(Number):[0],strings:u.str(t)||n?r.split(e):[]}}function q(t){return m(t?y(u.arr(t)?t.map(b):b(t)):[],(function(t,n,e){return e.indexOf(t)===n}))}function W(t){var n=q(t);return n.map((function(t,e){return{target:t,id:e,total:n.length,transforms:{list:S(t)}}}))}function H(t,n){var e=x(n);if(/^spring/.test(e.easing)&&(e.duration=c(e.easing)),u.arr(t)){var r=t.length;2===r&&!u.obj(t[0])?t={value:t}:u.fnc(n.duration)||(e.duration=n.duration/r)}var i=u.arr(t)?t:[t];return i.map((function(t,e){var r=u.obj(t)&&!u.pth(t)?t:{value:t};return u.und(r.delay)&&(r.delay=e?0:n.delay),u.und(r.endDelay)&&(r.endDelay=e===i.length-1?n.endDelay:0),r})).map((function(t){return M(t,e)}))}function X(t,n){var e=[],r=n.keyframes;for(var i in r&&(n=M(function(t){for(var n=m(y(t.map((function(t){return Object.keys(t)}))),(function(t){return u.key(t)})).reduce((function(t,n){return t.indexOf(n)<0&&t.push(n),t}),[]),e={},r=function(r){var i=n[r];e[i]=t.map((function(t){var n={};for(var e in t)u.key(e)?e==i&&(n.value=t[e]):n[e]=t[e];return n}))},i=0;i-1&&(K.splice(o,1),e=K.length)}else i.tick(n);r++}t()}else J=cancelAnimationFrame(J)}return t}();function et(e){void 0===e&&(e={});var r,o=0,a=0,u=0,s=0,c=null;function f(t){var n=window.Promise&&new Promise((function(t){return c=t}));return t.finished=n,n}var l=function(e){var r=_(t,e),i=_(n,e),o=X(i,e),a=W(e.targets),u=Q(a,o),s=V(u,i),c=U;return U++,M(r,{id:c,children:[],animatables:a,animations:u,duration:s.duration,delay:s.delay,endDelay:s.endDelay})}(e);f(l);function d(){var t=l.direction;"alternate"!==t&&(l.direction="normal"!==t?"normal":"reverse"),l.reversed=!l.reversed,r.forEach((function(t){return t.reversed=l.reversed}))}function h(t){return l.reversed?l.duration-t:t}function p(){o=0,a=h(l.currentTime)*(1/et.speed)}function g(t,n){n&&n.seek(t-n.timelineOffset)}function v(t){for(var n=0,e=l.animations,r=e.length;n2||(w=Math.round(w*p)/p)),g.push(w)}var M=h.length;if(M){y=h[0];for(var C=0;C0&&(l.began=!0,y("begin")),!l.loopBegan&&l.currentTime>0&&(l.loopBegan=!0,y("loopBegin")),m<=e&&0!==l.currentTime&&v(0),(m>=p&&l.currentTime!==n||!n)&&v(n),m>e&&m=n&&(a=0,l.remaining&&!0!==l.remaining&&l.remaining--,l.remaining?(o=u,y("loopComplete"),l.loopBegan=!1,"alternate"===l.direction&&d()):(l.paused=!0,l.completed||(l.completed=!0,y("loopComplete"),y("complete"),!l.passThrough&&"Promise"in window&&(c(),f(l)))))}return l.reset=function(){var t=l.direction;l.passThrough=!1,l.currentTime=0,l.progress=0,l.paused=!0,l.began=!1,l.loopBegan=!1,l.changeBegan=!1,l.completed=!1,l.changeCompleted=!1,l.reversePlayback=!1,l.reversed="reverse"===t,l.remaining=l.loop,r=l.children;for(var n=s=r.length;n--;)l.children[n].reset();(l.reversed&&!0!==l.loop||"alternate"===t&&1===l.loop)&&l.remaining++,v(l.reversed?l.duration:0)},l.set=function(t,n){return G(t,n),l},l.tick=function(t){u=t,o||(o=u),b((u+(a-o))*et.speed)},l.seek=function(t){b(h(t))},l.pause=function(){l.paused=!0,p()},l.play=function(){l.paused&&(l.completed&&l.reset(),l.paused=!1,K.push(l),p(),J||nt())},l.reverse=function(){d(),l.completed=!l.reversed,p()},l.restart=function(){l.reset(),l.play()},l.reset(),l.autoplay&&l.play(),l}function rt(t,n){for(var e=n.length;e--;)w(t,n[e].animatable.target)&&n.splice(e,1)}"undefined"!=typeof document&&document.addEventListener("visibilitychange",(function(){document.hidden?(K.forEach((function(t){return t.pause()})),tt=K.slice(0),et.running=K=[]):tt.forEach((function(t){return t.play()}))})),et.version="3.2.0",et.speed=1,et.running=K,et.remove=function(t){for(var n=q(t),e=K.length;e--;){var r=K[e],i=r.animations,o=r.children;rt(n,i);for(var a=o.length;a--;){var u=o[a],s=u.animations;rt(n,s),s.length||u.children.length||o.splice(a,1)}i.length||o.length||r.pause()}},et.get=T,et.set=G,et.convertPx=F,et.path=function(t,n){var e=u.str(t)?v(t)[0]:t,r=n||100;return function(t){return{property:t,el:e,svg:z(e),totalLength:I(e)*(r/100)}}},et.setDashoffset=function(t){var n=I(t);return t.setAttribute("stroke-dasharray",n),n},et.stagger=function(t,n){void 0===n&&(n={});var e=n.direction||"normal",r=n.easing?g(n.easing):null,i=n.grid,o=n.axis,a=n.from||0,s="first"===a,c="center"===a,f="last"===a,l=u.arr(t),d=l?parseFloat(t[0]):parseFloat(t),h=l?parseFloat(t[1]):0,p=k(l?t[1]:t)||0,v=n.start||0+(l?d:0),m=[],y=0;return function(t,n,u){if(s&&(a=0),c&&(a=(u-1)/2),f&&(a=u-1),!m.length){for(var g=0;g-1&&K.splice(o,1);for(var c=0;c12)throw new Error("data.length must between 3 and 12");this._count=0,this._rotation=0,this._weight=[],this._weightSum=0,this._running=!1,this._checkPrize(),this.option.draw&&this.draw()}_checkPrize(){const t=this.option.data;for(const n in t){const e=t[n];t[n]="string"==typeof e?{text:e,chance:1}:{...t[n],text:e.text||n,chance:e.chance>0?e.chance:1},this._weight.push(Number(t[n].chance)),this._weightSum+=Number(t[n].chance)}}draw(){const t=this.option;this._center=t.pos.map(n=>n+t.radius);const n={width:2*t.radius,height:2*t.radius};"svg"!==t.el.tagName?(this._svg=function(t={}){return at(null,t),ut("svg",t)}(n),t.el.appendChild(this._svg)):(this._svg=t.el,function(t,n={}){if("svg"===t.tagName){at(t,n);for(const e in n)t.setAttribute(e,n[e])}}(t.el,n)),this._deg=360/t.data.length,t.image&&this._drawResource(),this._drawDefault(),this._animeFunc()}_drawDefault(){if(this._turntable&&this._button)return;const t=this.option,n=bt[t.theme]||bt.default;var e;t.color={...n,...t.color},t.inRadius?t.inRadius>t.radius&&(t.inRadius=t.radius):t.inRadius=(e=t.radius)<50?e:e<100?e-10:9*Math.round(e/10),this._turntable||this._drawTurntable(),this._button||this._drawButton()}_drawResource(){const t=this.option,n=t.image;if("object"==typeof n&&Object.keys(n).length>0&&(n.turntable&&"string"==typeof n.turntable&&(this._turntable=dt(n.turntable,{width:2*t.radius,height:2*t.radius,x:t.pos[0],y:t.pos[1]}),this._svg.appendChild(this._turntable)),n.button&&"string"==typeof n.button)){n.offset&&"number"==typeof n.offset||(n.offset=0);const e=[50,50],r=e[1]*t.buttonWidth/e[0];this._button=dt(n.button,{width:t.buttonWidth,height:r,x:this._center[0]-t.buttonWidth/2,y:this._center[1]+n.offset-r/2}),this._svg.appendChild(this._button)}}_drawTurntable(){if(this._turntable)return;const t=this.option;this._svg.appendChild(ft(this._center[0],this._center[1],t.radius,{fill:t.color.border})),this._svg.appendChild(ft(this._center[0],this._center[1],t.inRadius,{fill:t.color.prize})),this._turntable=lt(),this._svg.appendChild(this._turntable);for(const n of t.data){const[e,r]=wt(this._center[0],this._center[1],t.inRadius,-this._deg/2,this._deg/2),i=ht(e,{fill:n.color||t.color.prize,stroke:t.color.line,strokeWidth:2});let o=n.fontSize||t.fontSize;if(!o){let e=0;for(let t=0;tr*t.textBottomPercentage?r*t.textBottomPercentage/e*2:16}const a=gt(n.text,{x:this._center[0],y:t.pos[1]+t.radius-t.inRadius*t.textBottomPercentage,fontSize:o,fill:n.fontColor||t.color.prizeFont}),u=lt([i,a]);pt(u,mt(this._deg*t.data.indexOf(n)),this._center[0],this._center[1]),this._turntable.appendChild(u),vt(a,-a.getComputedTextLength()/2,0)}}_drawButton(){if(this._button)return;const t=this.option;if(t.button&&"string"==typeof t.button)return;const n=t.buttonWidth/2,e=this._center,r=(180-t.buttonDeg)/2,[i,,,o]=wt(e[0],e[1],n,r-360,360-r),a=[e[0],e[1]-n/Math.cos(mt(r))],u=ht(`${i} L ${a[0]} ${a[1]} L ${o.x} ${o.y} L ${e[0]} ${e[1]}`,{fill:t.color.button});!function(t,n,e={}){const r="drop-shadow-"+it++,i=ut("defs"),o=ut("filter",{id:r,filterUnits:"userSpaceOnUse"}),a=ut("feGaussianBlur",{in:"SourceAlpha",stdDeviation:e.blurStdDeviation||0}),u=ut("feOffset",{dx:e.offsetDx||0,dy:e.offsetDy||0}),s=ut("feComponentTransfer"),c=ut("feFuncA",{type:"linear",slope:.5});s.appendChild(c);const f=ut("feMerge"),l=ut("feMergeNode"),d=ut("feMergeNode",{in:"SourceGraphic"});f.appendChild(l),f.appendChild(d),o.appendChild(a),o.appendChild(u),o.appendChild(s),o.appendChild(f),i.appendChild(o),t.appendChild(i),n.setAttribute("filter",`url(#${r})`)}(this._svg,u,{blurStdDeviation:3,offsetDy:3});let s=null;if(""!==t.buttonText){const r=2*n*.8;let i=t.buttonFontSize;if(!i){let n=0;for(let e=0;er?r/n*2:16}s=gt(t.buttonText,{x:e[0],y:e[1],fontSize:i,fill:t.color.buttonFont})}this._button=lt([u,s]),this._svg.appendChild(this._button),vt(s,-s.getComputedTextLength()/2,0)}_animeFunc(){const t=this.option;this._turntable.style["transform-origin"]="center",this._button.style.cursor="pointer",this._button.style["transform-origin"]="center",this._button.addEventListener("mouseover",()=>{t.onButtonHover&&"function"==typeof t.onButtonHover?t.onButtonHover(et,this._button):et({targets:this._button,scale:1.2,duration:500})}),this._button.addEventListener("mouseout",()=>{et({targets:this._button,scale:1,duration:500})}),this._button.addEventListener("click",()=>{this._run()})}_run(){if(this._running)return;const t=this.option;if(t.limit>0&&this._count>=t.limit)return void(t.onFail&&"function"==typeof t.onFail&&t.onFail());const n=n=>{if(this._rotation>0){const t=360-this._rotation%360;this._rotation+=t}var e,r;this._rotation+=(e=n,r=this._deg,360*t.turn+e*r),et({targets:this._turntable,rotate:t.clockwise?this._rotation+"deg":"-"+this._rotation+"deg",duration:t.duration,begin:()=>{this._running=!0},complete:()=>{if(this._running=!1,++this._count,t.onSuccess&&"function"==typeof t.onSuccess){const e=t.clockwise?t.data[(t.data.length-n)%t.data.length]:t.data[n];t.onSuccess(e)}}})},e=Math.random()*this._weightSum;let r=0,i=0;for(const t in this._weight)if(r+=this._weight[t],r>e){i=t,n(i);break}}}})); +!function(t,n){"object"==typeof exports&&"undefined"!=typeof module?module.exports=n():"function"==typeof define&&define.amd?define(n):(t=t||self).Wheel=n()}(this,(function(){"use strict";function t(n){return(t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(n)}function n(t,n){if(!(t instanceof n))throw new TypeError("Cannot call a class as a function")}function e(t,n){for(var e=0;et.length)&&(n=t.length);for(var e=0,r=new Array(n);e=t.length?{done:!0}:{done:!1,value:t[n++]}},e:function(t){throw t},f:e}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var r,o,a=!0,i=!1;return{s:function(){r=t[Symbol.iterator]()},n:function(){var t=r.next();return a=t.done,t},e:function(t){i=!0,o=t},f:function(){try{a||null==r.return||r.return()}finally{if(i)throw o}}}}var f={update:null,begin:null,loopBegin:null,changeBegin:null,change:null,changeComplete:null,loopComplete:null,complete:null,loop:1,direction:"normal",autoplay:!0,timelineOffset:0},d={duration:1e3,delay:0,endDelay:0,easing:"easeOutElastic(1, .5)",round:0},h=["translateX","translateY","translateZ","rotate","rotateX","rotateY","rotateZ","scale","scaleX","scaleY","scaleZ","skew","skewX","skewY","perspective","matrix","matrix3d"],p={CSS:{},springs:{}};function v(t,n,e){return Math.min(Math.max(t,n),e)}function g(t,n){return t.indexOf(n)>-1}function m(t,n){return t.apply(null,n)}var y={arr:function(t){return Array.isArray(t)},obj:function(t){return g(Object.prototype.toString.call(t),"Object")},pth:function(t){return y.obj(t)&&t.hasOwnProperty("totalLength")},svg:function(t){return t instanceof SVGElement},inp:function(t){return t instanceof HTMLInputElement},dom:function(t){return t.nodeType||y.svg(t)},str:function(t){return"string"==typeof t},fnc:function(t){return"function"==typeof t},und:function(t){return void 0===t},hex:function(t){return/(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(t)},rgb:function(t){return/^rgb/.test(t)},hsl:function(t){return/^hsl/.test(t)},col:function(t){return y.hex(t)||y.rgb(t)||y.hsl(t)},key:function(t){return!f.hasOwnProperty(t)&&!d.hasOwnProperty(t)&&"targets"!==t&&"keyframes"!==t}};function b(t){var n=/\(([^)]+)\)/.exec(t);return n?n[1].split(",").map((function(t){return parseFloat(t)})):[]}function w(t,n){var e=b(t),r=v(y.und(e[0])?1:e[0],.1,100),o=v(y.und(e[1])?100:e[1],.1,100),a=v(y.und(e[2])?10:e[2],.1,100),i=v(y.und(e[3])?0:e[3],.1,100),u=Math.sqrt(o/r),c=a/(2*Math.sqrt(o*r)),s=c<1?u*Math.sqrt(1-c*c):0,l=c<1?(c*u-i)/s:-i+u;function f(t){var e=n?n*t/1e3:t;return e=c<1?Math.exp(-e*c*u)*(1*Math.cos(s*e)+l*Math.sin(s*e)):(1+l*e)*Math.exp(-e*u),0===t||1===t?t:1-e}return n?f:function(){var n=p.springs[t];if(n)return n;for(var e=0,r=0;;)if(1===f(e+=1/6)){if(++r>=16)break}else r=0;var o=e*(1/6)*1e3;return p.springs[t]=o,o}}function x(t){return void 0===t&&(t=10),function(n){return Math.ceil(v(n,1e-6,1)*t)*(1/t)}}var _,M,O=function(){function t(t,n){return 1-3*n+3*t}function n(t,n){return 3*n-6*t}function e(t){return 3*t}function r(r,o,a){return((t(o,a)*r+n(o,a))*r+e(o))*r}function o(r,o,a){return 3*t(o,a)*r*r+2*n(o,a)*r+e(o)}return function(t,n,e,a){if(0<=t&&t<=1&&0<=e&&e<=1){var i=new Float32Array(11);if(t!==n||e!==a)for(var u=0;u<11;++u)i[u]=r(.1*u,t,e);return function(o){return t===n&&e===a||0===o||1===o?o:r(c(o),n,a)}}function c(n){for(var a=0,u=1;10!==u&&i[u]<=n;++u)a+=.1;--u;var c=a+.1*((n-i[u])/(i[u+1]-i[u])),s=o(c,t,e);return s>=.001?function(t,n,e,a){for(var i=0;i<4;++i){var u=o(n,e,a);if(0===u)return n;n-=(r(n,e,a)-t)/u}return n}(n,c,t,e):0===s?c:function(t,n,e,o,a){var i,u,c=0;do{(i=r(u=n+(e-n)/2,o,a)-t)>0?e=u:n=u}while(Math.abs(i)>1e-7&&++c<10);return u}(n,a,a+.1,t,e)}}}(),k=(_={linear:function(){return function(t){return t}}},M={Sine:function(){return function(t){return 1-Math.cos(t*Math.PI/2)}},Circ:function(){return function(t){return 1-Math.sqrt(1-t*t)}},Back:function(){return function(t){return t*t*(3*t-2)}},Bounce:function(){return function(t){for(var n,e=4;t<((n=Math.pow(2,--e))-1)/11;);return 1/Math.pow(4,3-e)-7.5625*Math.pow((3*n-2)/22-t,2)}},Elastic:function(t,n){void 0===t&&(t=1),void 0===n&&(n=.5);var e=v(t,1,10),r=v(n,.1,2);return function(t){return 0===t||1===t?t:-e*Math.pow(2,10*(t-1))*Math.sin((t-1-r/(2*Math.PI)*Math.asin(1/e))*(2*Math.PI)/r)}}},["Quad","Cubic","Quart","Quint","Expo"].forEach((function(t,n){M[t]=function(){return function(t){return Math.pow(t,n+2)}}})),Object.keys(M).forEach((function(t){var n=M[t];_["easeIn"+t]=n,_["easeOut"+t]=function(t,e){return function(r){return 1-n(t,e)(1-r)}},_["easeInOut"+t]=function(t,e){return function(r){return r<.5?n(t,e)(2*r)/2:1-n(t,e)(-2*r+2)/2}}})),_);function C(t,n){if(y.fnc(t))return t;var e=t.split("(")[0],r=k[e],o=b(t);switch(e){case"spring":return w(t,n);case"cubicBezier":return m(O,o);case"steps":return m(x,o);default:return m(r,o)}}function S(t){try{return document.querySelectorAll(t)}catch(t){return}}function P(t,n){for(var e=t.length,r=arguments.length>=2?arguments[1]:void 0,o=[],a=0;a1&&(e-=1),e<1/6?t+6*(n-t)*e:e<.5?n:e<2/3?t+(n-t)*(2/3-e)*6:t}if(0==i)n=e=r=u;else{var l=u<.5?u*(1+i):u+i-u*i,f=2*u-l;n=s(f,l,a+1/3),e=s(f,l,a),r=s(f,l,a-1/3)}return"rgba("+255*n+","+255*e+","+255*r+","+c+")"}(t):void 0;var n,e}function D(t){var n=/[+-]?\d*\.?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?(%|px|pt|em|rem|in|cm|mm|ex|ch|pc|vw|vh|vmin|vmax|deg|rad|turn)?$/.exec(t);if(n)return n[1]}function L(t,n){return y.fnc(t)?t(n.target,n.id,n.total):t}function N(t,n){return t.getAttribute(n)}function z(t,n,e){if(T([e,"deg","rad","turn"],D(n)))return n;var r=p.CSS[n+e];if(!y.und(r))return r;var o=document.createElement(t.tagName),a=t.parentNode&&t.parentNode!==document?t.parentNode:document.body;a.appendChild(o),o.style.position="absolute",o.style.width=100+e;var i=100/o.offsetWidth;a.removeChild(o);var u=i*parseFloat(n);return p.CSS[n+e]=u,u}function R(t,n,e){if(n in t.style){var r=n.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase(),o=t.style[n]||getComputedStyle(t).getPropertyValue(r)||"0";return e?z(t,o,e):o}}function q(t,n){return y.dom(t)&&!y.inp(t)&&(N(t,n)||y.svg(t)&&t[n])?"attribute":y.dom(t)&&T(h,n)?"transform":y.dom(t)&&"transform"!==n&&R(t,n)?"css":null!=t[n]?"object":void 0}function W(t){if(y.dom(t)){for(var n,e=t.style.transform||"",r=/(\w+)\(([^)]*)\)/g,o=new Map;n=r.exec(e);)o.set(n[1],n[2]);return o}}function $(t,n,e,r){var o=g(n,"scale")?1:0+function(t){return g(t,"translate")||"perspective"===t?"px":g(t,"rotate")||g(t,"skew")?"deg":void 0}(n),a=W(t).get(n)||o;return e&&(e.transforms.list.set(n,a),e.transforms.last=n),r?z(t,a,r):a}function H(t,n,e,r){switch(q(t,n)){case"transform":return $(t,n,r,e);case"css":return R(t,n,e);case"attribute":return N(t,n);default:return t[n]||0}}function X(t,n){var e=/^(\*=|\+=|-=)/.exec(t);if(!e)return t;var r=D(t)||0,o=parseFloat(n),a=parseFloat(t.replace(e[0],""));switch(e[0][0]){case"+":return o+a+r;case"-":return o-a+r;case"*":return o*a+r}}function Y(t,n){if(y.col(t))return I(t);if(/\s/g.test(t))return t;var e=D(t),r=e?t.substr(0,t.length-e.length):t;return n?r+n:r}function Z(t,n){return Math.sqrt(Math.pow(n.x-t.x,2)+Math.pow(n.y-t.y,2))}function G(t){for(var n,e=t.points,r=0,o=0;o0&&(r+=Z(n,a)),n=a}return r}function Q(t){if(t.getTotalLength)return t.getTotalLength();switch(t.tagName.toLowerCase()){case"circle":return function(t){return 2*Math.PI*N(t,"r")}(t);case"rect":return function(t){return 2*N(t,"width")+2*N(t,"height")}(t);case"line":return function(t){return Z({x:N(t,"x1"),y:N(t,"y1")},{x:N(t,"x2"),y:N(t,"y2")})}(t);case"polyline":return G(t);case"polygon":return function(t){var n=t.points;return G(t)+Z(n.getItem(n.numberOfItems-1),n.getItem(0))}(t)}}function U(t,n){var e=n||{},r=e.el||function(t){for(var n=t.parentNode;y.svg(n)&&y.svg(n.parentNode);)n=n.parentNode;return n}(t),o=r.getBoundingClientRect(),a=N(r,"viewBox"),i=o.width,u=o.height,c=e.viewBox||(a?a.split(" "):[0,0,i,u]);return{el:r,viewBox:c,x:c[0]/1,y:c[1]/1,w:i/c[2],h:u/c[3]}}function V(t,n){function e(e){void 0===e&&(e=0);var r=n+e>=1?n+e:0;return t.el.getPointAtLength(r)}var r=U(t.el,t.svg),o=e(),a=e(-1),i=e(1);switch(t.property){case"x":return(o.x-r.x)*r.w;case"y":return(o.y-r.y)*r.h;case"angle":return 180*Math.atan2(i.y-a.y,i.x-a.x)/Math.PI}}function J(t,n){var e=/[+-]?\d*\.?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/g,r=Y(y.pth(t)?t.totalLength:t,n)+"";return{original:r,numbers:r.match(e)?r.match(e).map(Number):[0],strings:y.str(t)||n?r.split(e):[]}}function K(t){return P(t?A(y.arr(t)?t.map(j):j(t)):[],(function(t,n,e){return e.indexOf(t)===n}))}function tt(t){var n=K(t);return n.map((function(t,e){return{target:t,id:e,total:n.length,transforms:{list:W(t)}}}))}function nt(t,n){var e=B(n);if(/^spring/.test(e.easing)&&(e.duration=w(e.easing)),y.arr(t)){var r=t.length;2===r&&!y.obj(t[0])?t={value:t}:y.fnc(n.duration)||(e.duration=n.duration/r)}var o=y.arr(t)?t:[t];return o.map((function(t,e){var r=y.obj(t)&&!y.pth(t)?t:{value:t};return y.und(r.delay)&&(r.delay=e?0:n.delay),y.und(r.endDelay)&&(r.endDelay=e===o.length-1?n.endDelay:0),r})).map((function(t){return F(t,e)}))}function et(t,n){var e=[],r=n.keyframes;for(var o in r&&(n=F(function(t){for(var n=P(A(t.map((function(t){return Object.keys(t)}))),(function(t){return y.key(t)})).reduce((function(t,n){return t.indexOf(n)<0&&t.push(n),t}),[]),e={},r=function(r){var o=n[r];e[o]=t.map((function(t){var n={};for(var e in t)y.key(e)?e==o&&(n.value=t[e]):n[e]=t[e];return n}))},o=0;o-1&&(lt.splice(a,1),e=lt.length)}else o.tick(n);r++}t()}else st=cancelAnimationFrame(st)}return t}();function ht(t){void 0===t&&(t={});var n,e=0,r=0,o=0,a=0,i=null;function u(t){var n=window.Promise&&new Promise((function(t){return i=t}));return t.finished=n,n}var c=function(t){var n=E(f,t),e=E(d,t),r=et(e,t),o=tt(t.targets),a=it(o,r),i=ut(a,e),u=ct;return ct++,F(n,{id:u,children:[],animatables:o,animations:a,duration:i.duration,delay:i.delay,endDelay:i.endDelay})}(t);u(c);function s(){var t=c.direction;"alternate"!==t&&(c.direction="normal"!==t?"normal":"reverse"),c.reversed=!c.reversed,n.forEach((function(t){return t.reversed=c.reversed}))}function l(t){return c.reversed?c.duration-t:t}function h(){e=0,r=l(c.currentTime)*(1/ht.speed)}function p(t,n){n&&n.seek(t-n.timelineOffset)}function g(t){for(var n=0,e=c.animations,r=e.length;n2||(b=Math.round(b*h)/h)),p.push(b)}var _=d.length;if(_){m=d[0];for(var M=0;M<_;M++){d[M];var O=d[M+1],k=p[M];isNaN(k)||(m+=O?k+O:k+" ")}}else m=p[0];ot[o.type](a.target,o.property,m,a.transforms),o.currentValue=m,n++}}function m(t){c[t]&&!c.passThrough&&c[t](c)}function y(t){var f=c.duration,d=c.delay,h=f-c.endDelay,y=l(t);c.progress=v(y/f*100,0,100),c.reversePlayback=y0&&(c.began=!0,m("begin")),!c.loopBegan&&c.currentTime>0&&(c.loopBegan=!0,m("loopBegin")),y<=d&&0!==c.currentTime&&g(0),(y>=h&&c.currentTime!==f||!f)&&g(f),y>d&&y=f&&(r=0,c.remaining&&!0!==c.remaining&&c.remaining--,c.remaining?(e=o,m("loopComplete"),c.loopBegan=!1,"alternate"===c.direction&&s()):(c.paused=!0,c.completed||(c.completed=!0,m("loopComplete"),m("complete"),!c.passThrough&&"Promise"in window&&(i(),u(c)))))}return c.reset=function(){var t=c.direction;c.passThrough=!1,c.currentTime=0,c.progress=0,c.paused=!0,c.began=!1,c.loopBegan=!1,c.changeBegan=!1,c.completed=!1,c.changeCompleted=!1,c.reversePlayback=!1,c.reversed="reverse"===t,c.remaining=c.loop,n=c.children;for(var e=a=n.length;e--;)c.children[e].reset();(c.reversed&&!0!==c.loop||"alternate"===t&&1===c.loop)&&c.remaining++,g(c.reversed?c.duration:0)},c.set=function(t,n){return at(t,n),c},c.tick=function(t){o=t,e||(e=o),y((o+(r-e))*ht.speed)},c.seek=function(t){y(l(t))},c.pause=function(){c.paused=!0,h()},c.play=function(){c.paused&&(c.completed&&c.reset(),c.paused=!1,lt.push(c),h(),st||dt())},c.reverse=function(){s(),c.completed=!c.reversed,h()},c.restart=function(){c.reset(),c.play()},c.reset(),c.autoplay&&c.play(),c}function pt(t,n){for(var e=n.length;e--;)T(t,n[e].animatable.target)&&n.splice(e,1)}"undefined"!=typeof document&&document.addEventListener("visibilitychange",(function(){document.hidden?(lt.forEach((function(t){return t.pause()})),ft=lt.slice(0),ht.running=lt=[]):ft.forEach((function(t){return t.play()}))})),ht.version="3.2.0",ht.speed=1,ht.running=lt,ht.remove=function(t){for(var n=K(t),e=lt.length;e--;){var r=lt[e],o=r.animations,a=r.children;pt(n,o);for(var i=a.length;i--;){var u=a[i],c=u.animations;pt(n,c),c.length||u.children.length||a.splice(i,1)}o.length||a.length||r.pause()}},ht.get=H,ht.set=at,ht.convertPx=z,ht.path=function(t,n){var e=y.str(t)?S(t)[0]:t,r=n||100;return function(t){return{property:t,el:e,svg:U(e),totalLength:Q(e)*(r/100)}}},ht.setDashoffset=function(t){var n=Q(t);return t.setAttribute("stroke-dasharray",n),n},ht.stagger=function(t,n){void 0===n&&(n={});var e=n.direction||"normal",r=n.easing?C(n.easing):null,o=n.grid,a=n.axis,i=n.from||0,u="first"===i,c="center"===i,s="last"===i,l=y.arr(t),f=l?parseFloat(t[0]):parseFloat(t),d=l?parseFloat(t[1]):0,h=D(l?t[1]:t)||0,p=n.start||0+(l?f:0),v=[],g=0;return function(t,n,m){if(u&&(i=0),c&&(i=(m-1)/2),s&&(i=m-1),!v.length){for(var y=0;y-1&<.splice(o,1);for(var u=0;u1&&void 0!==arguments[1]?arguments[1]:{},e=document.createElementNS("http://www.w3.org/2000/svg",t);for(var r in n)e.setAttribute(r,n[r]);return e}function bt(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,e=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1,o=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0,a=arguments.length>5&&void 0!==arguments[5]?arguments[5]:0;return{a:t,b:n,c:e,d:r,e:o,f:a}}function wt(t){var n=t.hasAttribute("transform");if(!n||n.indexOf("matrix")<0)return bt();var e=n.split(",");return bt.apply(void 0,u(e))}function xt(t,n,e){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};return r.cx=t,r.cy=n,r.r=e,yt("circle",r)}function _t(){var t,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=yt("g",e),o=l(n);try{for(o.s();!(t=o.n()).done;){var a=t.value;r.appendChild(a)}}catch(t){o.e(t)}finally{o.f()}return r}function Mt(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return n.href=t,yt("image",n)}function Ot(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return n.d=t,yt("path",n)}function kt(t,n){var e=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,o=Math.cos(n),a=Math.sin(n),i=wt(t),u=i.a,c=i.b,s=i.c,l=i.d,f=i.e,d=i.f,h=u*o-c*a,p=c*o+u*a,v=s*o-l*a,g=l*o+s*a,m=f*o-d*a+r*a-e*o+e,y=d*o+f*a-e*a-r*o+r;t.setAttribute("transform","matrix(".concat(h,",").concat(p,",").concat(v,",").concat(g,",").concat(m,",").concat(y,")"))}function Ct(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},e=yt("text",n);return e.textContent=t,e}function St(t,n){var e=arguments.length>2&&void 0!==arguments[2]?arguments[2]:n,r=wt(t),o=r.a,a=r.b,i=r.c,u=r.d,c=r.e,s=r.f;t.setAttribute("transform","matrix(".concat(o,",").concat(a,",").concat(i,",").concat(u,",").concat(c+n,",").concat(s+e,")"))}function Pt(t){return t*Math.PI/180}function At(t,n,e,r){var o=Pt(r-90);return{x:t+e*Math.cos(o),y:n+e*Math.sin(o)}}var jt={default:{border:"red",prize:"gold",button:"darkorange",line:"red",prizeFont:"red",buttonFont:"white"},light:{border:"orange",prize:"lightyellow",button:"tomato",line:"orange",prizeFont:"orange",buttonFont:"white"},dark:{border:"silver",prize:"dimgray",button:"darkslategray",line:"silver",prizeFont:"silver",buttonFont:"lightyellow"}};function Tt(t,n,e,r,o){var a=At(t,n,e,o),i=At(t,n,e,r),u=o-r<=180?0:1;return["M ".concat(a.x," ").concat(a.y," A ").concat(e," ").concat(e," 0 ").concat(u," 0 ").concat(i.x," ").concat(i.y," L ").concat(t," ").concat(n," L ").concat(a.x," ").concat(a.y),a.x-i.x,a,i]}return function(){function r(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(n(this,r),this.option=a({pos:[0,0],radius:100,buttonWidth:50,buttonDeg:80,buttonText:"Draw",textBottomPercentage:.6,limit:0,duration:5e3,turn:4,clockwise:!0,draw:!0,theme:"default"},t),!this.option.el)throw new Error("el is undefined");if(!this.option.data)throw new Error("data is undefined");var e=this.option.data.length;if(e<3||e>12)throw new Error("data.length must between 3 and 12");this._count=0,this._rotation=0,this._weight=[],this._weightSum=0,this._running=!1,this._checkPrize(),this.option.draw&&this.draw()}var o,u,c;return o=r,(u=[{key:"_checkPrize",value:function(){var t=this.option.data;for(var n in t){var e=t[n];t[n]="string"==typeof e?{text:e,chance:1}:a(a({},t[n]),{},{text:e.text||n,chance:e.chance>0?e.chance:1}),this._weight.push(Number(t[n].chance)),this._weightSum+=Number(t[n].chance)}}},{key:"draw",value:function(){var t=this.option;this._center=t.pos.map((function(n){return n+t.radius}));var n={width:2*t.radius,height:2*t.radius};"svg"!==t.el.tagName?(this._svg=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return mt(null,t),yt("svg",t)}(n),t.el.appendChild(this._svg)):(this._svg=t.el,function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("svg"===t.tagName)for(var e in mt(t,n),n)t.setAttribute(e,n[e])}(t.el,n)),this._deg=360/t.data.length,t.image&&this._drawResource(),this._drawDefault(),this._animeFunc()}},{key:"_drawDefault",value:function(){if(!this._turntable||!this._button){var t,n=this.option,e=jt[n.theme]||jt.default;n.color=a(a({},e),n.color),n.inRadius?n.inRadius>n.radius&&(n.inRadius=n.radius):n.inRadius=(t=n.radius)<50?t:t<100?t-10:9*Math.round(t/10),this._turntable||this._drawTurntable(),this._button||this._drawButton()}}},{key:"_drawResource",value:function(){var n=this.option,e=n.image;if("object"===t(e)&&Object.keys(e).length>0&&(e.turntable&&"string"==typeof e.turntable&&(this._turntable=Mt(e.turntable,{width:2*n.radius,height:2*n.radius,x:n.pos[0],y:n.pos[1]}),this._svg.appendChild(this._turntable)),e.button&&"string"==typeof e.button)){e.offset&&"number"==typeof e.offset||(e.offset=0);var r=[50,50],o=r[1]*n.buttonWidth/r[0];this._button=Mt(e.button,{width:n.buttonWidth,height:o,x:this._center[0]-n.buttonWidth/2,y:this._center[1]+e.offset-o/2}),this._svg.appendChild(this._button)}}},{key:"_drawTurntable",value:function(){if(!this._turntable){var t=this.option;this._svg.appendChild(xt(this._center[0],this._center[1],t.radius,{fill:t.color.border})),this._svg.appendChild(xt(this._center[0],this._center[1],t.inRadius,{fill:t.color.prize})),this._turntable=_t(),this._svg.appendChild(this._turntable);var n,e=l(t.data);try{for(e.s();!(n=e.n()).done;){var r=n.value,o=i(Tt(this._center[0],this._center[1],t.inRadius,-this._deg/2,this._deg/2),2),a=o[0],u=o[1],c=Ot(a,{fill:r.color||t.color.prize,stroke:t.color.line,strokeWidth:2}),s=r.fontSize||t.fontSize;if(!s){for(var f=0,d=0;du*t.textBottomPercentage?u*t.textBottomPercentage/f*2:16}var h=Ct(r.text,{x:this._center[0],y:t.pos[1]+t.radius-t.inRadius*t.textBottomPercentage,fontSize:s,fill:r.fontColor||t.color.prizeFont}),p=_t([c,h]);kt(p,Pt(this._deg*t.data.indexOf(r)),this._center[0],this._center[1]),this._turntable.appendChild(p),St(h,-h.getComputedTextLength()/2,0)}}catch(t){e.e(t)}finally{e.f()}}}},{key:"_drawButton",value:function(){if(!this._button){var t=this.option;if(!t.button||"string"!=typeof t.button){var n=t.buttonWidth/2,e=this._center,r=(180-t.buttonDeg)/2,o=i(Tt(e[0],e[1],n,r-360,360-r),4),a=o[0],u=o[3],c=[e[0],e[1]-n/Math.cos(Pt(r))],s=Ot("".concat(a," L ").concat(c[0]," ").concat(c[1]," L ").concat(u.x," ").concat(u.y," L ").concat(e[0]," ").concat(e[1]),{fill:t.color.button});!function(t,n,e,r,o){var a=arguments.length>5&&void 0!==arguments[5]?arguments[5]:1,i="drop-shadow-".concat(vt++),u=yt("defs"),c=yt("filter",{id:i,filterUnits:"userSpaceOnUse"}),s=yt("feGaussianBlur",{in:"SourceAlpha",stdDeviation:o}),l=yt("feOffset",{dx:e,dy:r}),f=yt("feMerge"),d=yt("feMergeNode"),h=yt("feMergeNode",{in:"SourceGraphic"});if(f.appendChild(d),f.appendChild(h),c.appendChild(s),c.appendChild(l),1!==a){var p=yt("feComponentTransfer"),v=yt("feFuncA",{type:"linear",slope:a});p.appendChild(v),c.appendChild(p)}c.appendChild(f),u.appendChild(c),t.appendChild(u),n.setAttribute("filter","url(#".concat(i,")"))}(this._svg,s,0,3,3,.5);var l=null;if(""!==t.buttonText){var f=2*n*.8,d=t.buttonFontSize;if(!d){for(var h=0,p=0;pf?f/h*2:16}l=Ct(t.buttonText,{x:e[0],y:e[1],fontSize:d,fill:t.color.buttonFont})}this._button=_t([s,l]),this._svg.appendChild(this._button),St(l,-l.getComputedTextLength()/2,0)}}}},{key:"_animeFunc",value:function(){var t=this,n=this.option;this._turntable.style["transform-origin"]="center",this._button.style.cursor="pointer",this._button.style["transform-origin"]="center",this._button.addEventListener("mouseover",(function(){n.onButtonHover&&"function"==typeof n.onButtonHover?n.onButtonHover(ht,t._button):ht({targets:t._button,scale:1.2,duration:500})})),this._button.addEventListener("mouseout",(function(){ht({targets:t._button,scale:1,duration:500})})),this._button.addEventListener("click",(function(){t._run()}))}},{key:"_run",value:function(){var t=this;if(!this._running){var n=this.option;if(n.limit>0&&this._count>=n.limit)n.onFail&&"function"==typeof n.onFail&&n.onFail();else{var e=function(e){if(t._rotation>0){var r=360-t._rotation%360;t._rotation+=r}t._rotation+=function(t,n,e){return 360*e+t*n}(e,t._deg,n.turn),ht({targets:t._turntable,rotate:n.clockwise?t._rotation+"deg":"-"+t._rotation+"deg",duration:n.duration,begin:function(){t._running=!0},complete:function(){if(t._running=!1,++t._count,n.onSuccess&&"function"==typeof n.onSuccess){var r=n.clockwise?n.data[(n.data.length-e)%n.data.length]:n.data[e];n.onSuccess(r)}}})},r=Math.random()*this._weightSum,o=0;for(var a in this._weight)if((o+=this._weight[a])>r){e(a);break}}}}}])&&e(o.prototype,u),c&&e(o,c),r}()})); diff --git a/package.json b/package.json index 0a50bd4..93d9ed8 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "lottery-wheel", - "version": "2.3.1", + "version": "2.4.0", "description": "A library helps you performing a wheel for lottery game.", "main": "src/index.js", "scripts": {