当前位置:   article > 正文

跟随鼠标3D倾斜

跟随鼠标3D倾斜
  1. 创建一个vanilla-tilt.js文件
  2. 将一下代码黏贴进去
    1. export var VanillaTilt = (function () {
    2. 'use strict';
    3. /**
    4. * Created by Sergiu Șandor (micku7zu) on 1/27/2017.
    5. * Original idea: https://github.com/gijsroge/tilt.js
    6. * MIT License.
    7. * Version 1.7.2
    8. */
    9. class VanillaTilt {
    10. constructor(element, settings = {}) {
    11. if (!(element instanceof Node)) {
    12. throw ("Can't initialize VanillaTilt because " + element + " is not a Node.");
    13. }
    14. this.width = null;
    15. this.height = null;
    16. this.clientWidth = null;
    17. this.clientHeight = null;
    18. this.left = null;
    19. this.top = null;
    20. // for Gyroscope sampling
    21. this.gammazero = null;
    22. this.betazero = null;
    23. this.lastgammazero = null;
    24. this.lastbetazero = null;
    25. this.transitionTimeout = null;
    26. this.updateCall = null;
    27. this.event = null;
    28. this.updateBind = this.update.bind(this);
    29. this.resetBind = this.reset.bind(this);
    30. this.element = element;
    31. this.settings = this.extendSettings(settings);
    32. this.reverse = this.settings.reverse ? -1 : 1;
    33. this.glare = VanillaTilt.isSettingTrue(this.settings.glare);
    34. this.glarePrerender = VanillaTilt.isSettingTrue(this.settings["glare-prerender"]);
    35. this.fullPageListening = VanillaTilt.isSettingTrue(this.settings["full-page-listening"]);
    36. this.gyroscope = VanillaTilt.isSettingTrue(this.settings.gyroscope);
    37. this.gyroscopeSamples = this.settings.gyroscopeSamples;
    38. this.elementListener = this.getElementListener();
    39. if (this.glare) {
    40. this.prepareGlare();
    41. }
    42. if (this.fullPageListening) {
    43. this.updateClientSize();
    44. }
    45. this.addEventListeners();
    46. this.reset();
    47. this.updateInitialPosition();
    48. }
    49. static isSettingTrue (setting) {
    50. return setting === "" || setting === true || setting === 1;
    51. }
    52. /**
    53. * Method returns element what will be listen mouse events
    54. * @return {Node}
    55. */
    56. getElementListener () {
    57. if (this.fullPageListening) {
    58. return window.document;
    59. }
    60. if (typeof this.settings["mouse-event-element"] === "string") {
    61. const mouseEventElement = document.querySelector(this.settings["mouse-event-element"]);
    62. if (mouseEventElement) {
    63. return mouseEventElement;
    64. }
    65. }
    66. if (this.settings["mouse-event-element"] instanceof Node) {
    67. return this.settings["mouse-event-element"];
    68. }
    69. return this.element;
    70. }
    71. /**
    72. * Method set listen methods for this.elementListener
    73. * @return {Node}
    74. */
    75. addEventListeners () {
    76. this.onMouseEnterBind = this.onMouseEnter.bind(this);
    77. this.onMouseMoveBind = this.onMouseMove.bind(this);
    78. this.onMouseLeaveBind = this.onMouseLeave.bind(this);
    79. this.onWindowResizeBind = this.onWindowResize.bind(this);
    80. this.onDeviceOrientationBind = this.onDeviceOrientation.bind(this);
    81. this.elementListener.addEventListener("mouseenter", this.onMouseEnterBind);
    82. this.elementListener.addEventListener("mouseleave", this.onMouseLeaveBind);
    83. this.elementListener.addEventListener("mousemove", this.onMouseMoveBind);
    84. if (this.glare || this.fullPageListening) {
    85. window.addEventListener("resize", this.onWindowResizeBind);
    86. }
    87. if (this.gyroscope) {
    88. window.addEventListener("deviceorientation", this.onDeviceOrientationBind);
    89. }
    90. }
    91. /**
    92. * Method remove event listeners from current this.elementListener
    93. */
    94. removeEventListeners () {
    95. this.elementListener.removeEventListener("mouseenter", this.onMouseEnterBind);
    96. this.elementListener.removeEventListener("mouseleave", this.onMouseLeaveBind);
    97. this.elementListener.removeEventListener("mousemove", this.onMouseMoveBind);
    98. if (this.gyroscope) {
    99. window.removeEventListener("deviceorientation", this.onDeviceOrientationBind);
    100. }
    101. if (this.glare || this.fullPageListening) {
    102. window.removeEventListener("resize", this.onWindowResizeBind);
    103. }
    104. }
    105. destroy () {
    106. clearTimeout(this.transitionTimeout);
    107. if (this.updateCall !== null) {
    108. cancelAnimationFrame(this.updateCall);
    109. }
    110. this.reset();
    111. this.removeEventListeners();
    112. this.element.vanillaTilt = null;
    113. delete this.element.vanillaTilt;
    114. this.element = null;
    115. }
    116. onDeviceOrientation (event) {
    117. if (event.gamma === null || event.beta === null) {
    118. return;
    119. }
    120. this.updateElementPosition();
    121. if (this.gyroscopeSamples > 0) {
    122. this.lastgammazero = this.gammazero;
    123. this.lastbetazero = this.betazero;
    124. if (this.gammazero === null) {
    125. this.gammazero = event.gamma;
    126. this.betazero = event.beta;
    127. } else {
    128. this.gammazero = (event.gamma + this.lastgammazero) / 2;
    129. this.betazero = (event.beta + this.lastbetazero) / 2;
    130. }
    131. this.gyroscopeSamples -= 1;
    132. }
    133. const totalAngleX = this.settings.gyroscopeMaxAngleX - this.settings.gyroscopeMinAngleX;
    134. const totalAngleY = this.settings.gyroscopeMaxAngleY - this.settings.gyroscopeMinAngleY;
    135. const degreesPerPixelX = totalAngleX / this.width;
    136. const degreesPerPixelY = totalAngleY / this.height;
    137. const angleX = event.gamma - (this.settings.gyroscopeMinAngleX + this.gammazero);
    138. const angleY = event.beta - (this.settings.gyroscopeMinAngleY + this.betazero);
    139. const posX = angleX / degreesPerPixelX;
    140. const posY = angleY / degreesPerPixelY;
    141. if (this.updateCall !== null) {
    142. cancelAnimationFrame(this.updateCall);
    143. }
    144. this.event = {
    145. clientX: posX + this.left,
    146. clientY: posY + this.top,
    147. };
    148. this.updateCall = requestAnimationFrame(this.updateBind);
    149. }
    150. onMouseEnter () {
    151. this.updateElementPosition();
    152. this.element.style.willChange = "transform";
    153. this.setTransition();
    154. }
    155. onMouseMove (event) {
    156. if (this.updateCall !== null) {
    157. cancelAnimationFrame(this.updateCall);
    158. }
    159. this.event = event;
    160. this.updateCall = requestAnimationFrame(this.updateBind);
    161. }
    162. onMouseLeave () {
    163. this.setTransition();
    164. if (this.settings.reset) {
    165. requestAnimationFrame(this.resetBind);
    166. }
    167. }
    168. reset () {
    169. this.event = {
    170. clientX: this.left + this.width / 2,
    171. clientY: this.top + this.height / 2
    172. };
    173. if (this.element && this.element.style) {
    174. this.element.style.transform = `perspective(${this.settings.perspective}px) ` +
    175. `rotateX(0deg) ` +
    176. `rotateY(0deg) ` +
    177. `scale3d(1, 1, 1)`;
    178. }
    179. this.resetGlare();
    180. }
    181. resetGlare () {
    182. if (this.glare) {
    183. this.glareElement.style.transform = "rotate(180deg) translate(-50%, -50%)";
    184. this.glareElement.style.opacity = "0";
    185. }
    186. }
    187. updateInitialPosition () {
    188. if (this.settings.startX === 0 && this.settings.startY === 0) {
    189. return;
    190. }
    191. this.onMouseEnter();
    192. if (this.fullPageListening) {
    193. this.event = {
    194. clientX: (this.settings.startX + this.settings.max) / (2 * this.settings.max) * this.clientWidth,
    195. clientY: (this.settings.startY + this.settings.max) / (2 * this.settings.max) * this.clientHeight
    196. };
    197. } else {
    198. this.event = {
    199. clientX: this.left + ((this.settings.startX + this.settings.max) / (2 * this.settings.max) * this.width),
    200. clientY: this.top + ((this.settings.startY + this.settings.max) / (2 * this.settings.max) * this.height)
    201. };
    202. }
    203. let backupScale = this.settings.scale;
    204. this.settings.scale = 1;
    205. this.update();
    206. this.settings.scale = backupScale;
    207. this.resetGlare();
    208. }
    209. getValues () {
    210. let x, y;
    211. if (this.fullPageListening) {
    212. x = this.event.clientX / this.clientWidth;
    213. y = this.event.clientY / this.clientHeight;
    214. } else {
    215. x = (this.event.clientX - this.left) / this.width;
    216. y = (this.event.clientY - this.top) / this.height;
    217. }
    218. x = Math.min(Math.max(x, 0), 1);
    219. y = Math.min(Math.max(y, 0), 1);
    220. let tiltX = (this.reverse * (this.settings.max - x * this.settings.max * 2)).toFixed(2);
    221. let tiltY = (this.reverse * (y * this.settings.max * 2 - this.settings.max)).toFixed(2);
    222. let angle = Math.atan2(this.event.clientX - (this.left + this.width / 2), -(this.event.clientY - (this.top + this.height / 2))) * (180 / Math.PI);
    223. return {
    224. tiltX: tiltX,
    225. tiltY: tiltY,
    226. percentageX: x * 100,
    227. percentageY: y * 100,
    228. angle: angle
    229. };
    230. }
    231. updateElementPosition () {
    232. let rect = this.element.getBoundingClientRect();
    233. this.width = this.element.offsetWidth;
    234. this.height = this.element.offsetHeight;
    235. this.left = rect.left;
    236. this.top = rect.top;
    237. }
    238. update () {
    239. let values = this.getValues();
    240. this.element.style.transform = "perspective(" + this.settings.perspective + "px) " +
    241. "rotateX(" + (this.settings.axis === "x" ? 0 : values.tiltY) + "deg) " +
    242. "rotateY(" + (this.settings.axis === "y" ? 0 : values.tiltX) + "deg) " +
    243. "scale3d(" + this.settings.scale + ", " + this.settings.scale + ", " + this.settings.scale + ")";
    244. if (this.glare) {
    245. this.glareElement.style.transform = `rotate(${values.angle}deg) translate(-50%, -50%)`;
    246. this.glareElement.style.opacity = `${values.percentageY * this.settings["max-glare"] / 100}`;
    247. }
    248. this.element.dispatchEvent(new CustomEvent("tiltChange", {
    249. "detail": values
    250. }));
    251. this.updateCall = null;
    252. }
    253. /**
    254. * Appends the glare element (if glarePrerender equals false)
    255. * and sets the default style
    256. */
    257. prepareGlare () {
    258. // If option pre-render is enabled we assume all html/css is present for an optimal glare effect.
    259. if (!this.glarePrerender) {
    260. // Create glare element
    261. const jsTiltGlare = document.createElement("div");
    262. jsTiltGlare.classList.add("js-tilt-glare");
    263. const jsTiltGlareInner = document.createElement("div");
    264. jsTiltGlareInner.classList.add("js-tilt-glare-inner");
    265. jsTiltGlare.appendChild(jsTiltGlareInner);
    266. this.element.appendChild(jsTiltGlare);
    267. }
    268. this.glareElementWrapper = this.element.querySelector(".js-tilt-glare");
    269. this.glareElement = this.element.querySelector(".js-tilt-glare-inner");
    270. if (this.glarePrerender) {
    271. return;
    272. }
    273. Object.assign(this.glareElementWrapper.style, {
    274. "position": "absolute",
    275. "top": "0",
    276. "left": "0",
    277. "width": "100%",
    278. "height": "100%",
    279. "overflow": "hidden",
    280. "pointer-events": "none"
    281. });
    282. Object.assign(this.glareElement.style, {
    283. "position": "absolute",
    284. "top": "50%",
    285. "left": "50%",
    286. "pointer-events": "none",
    287. "background-image": `linear-gradient(0deg, rgba(255,255,255,0) 0%, rgba(255,255,255,1) 100%)`,
    288. "transform": "rotate(180deg) translate(-50%, -50%)",
    289. "transform-origin": "0% 0%",
    290. "opacity": "0",
    291. });
    292. this.updateGlareSize();
    293. }
    294. updateGlareSize () {
    295. if (this.glare) {
    296. const glareSize = (this.element.offsetWidth > this.element.offsetHeight ? this.element.offsetWidth : this.element.offsetHeight) * 2;
    297. Object.assign(this.glareElement.style, {
    298. "width": `${glareSize}px`,
    299. "height": `${glareSize}px`,
    300. });
    301. }
    302. }
    303. updateClientSize () {
    304. this.clientWidth = window.innerWidth
    305. || document.documentElement.clientWidth
    306. || document.body.clientWidth;
    307. this.clientHeight = window.innerHeight
    308. || document.documentElement.clientHeight
    309. || document.body.clientHeight;
    310. }
    311. onWindowResize () {
    312. this.updateGlareSize();
    313. this.updateClientSize();
    314. }
    315. setTransition () {
    316. clearTimeout(this.transitionTimeout);
    317. this.element.style.transition = this.settings.speed + "ms " + this.settings.easing;
    318. if (this.glare) this.glareElement.style.transition = `opacity ${this.settings.speed}ms ${this.settings.easing}`;
    319. this.transitionTimeout = setTimeout(() => {
    320. this.element.style.transition = "";
    321. if (this.glare) {
    322. this.glareElement.style.transition = "";
    323. }
    324. }, this.settings.speed);
    325. }
    326. /**
    327. * Method return patched settings of instance
    328. * @param {boolean} settings.reverse - reverse the tilt direction
    329. * @param {number} settings.max - max tilt rotation (degrees)
    330. * @param {startX} settings.startX - the starting tilt on the X axis, in degrees. Default: 0
    331. * @param {startY} settings.startY - the starting tilt on the Y axis, in degrees. Default: 0
    332. * @param {number} settings.perspective - Transform perspective, the lower the more extreme the tilt gets
    333. * @param {string} settings.easing - Easing on enter/exit
    334. * @param {number} settings.scale - 2 = 200%, 1.5 = 150%, etc..
    335. * @param {number} settings.speed - Speed of the enter/exit transition
    336. * @param {boolean} settings.transition - Set a transition on enter/exit
    337. * @param {string|null} settings.axis - What axis should be disabled. Can be X or Y
    338. * @param {boolean} settings.glare - What axis should be disabled. Can be X or Y
    339. * @param {number} settings.max-glare - the maximum "glare" opacity (1 = 100%, 0.5 = 50%)
    340. * @param {boolean} settings.glare-prerender - false = VanillaTilt creates the glare elements for you, otherwise
    341. * @param {boolean} settings.full-page-listening - If true, parallax effect will listen to mouse move events on the whole document, not only the selected element
    342. * @param {string|object} settings.mouse-event-element - String selector or link to HTML-element what will be listen mouse events
    343. * @param {boolean} settings.reset - false = If the tilt effect has to be reset on exit
    344. * @param {gyroscope} settings.gyroscope - Enable tilting by deviceorientation events
    345. * @param {gyroscopeSensitivity} settings.gyroscopeSensitivity - Between 0 and 1 - The angle at which max tilt position is reached. 1 = 90deg, 0.5 = 45deg, etc..
    346. * @param {gyroscopeSamples} settings.gyroscopeSamples - How many gyroscope moves to decide the starting position.
    347. */
    348. extendSettings (settings) {
    349. let defaultSettings = {
    350. reverse: false,
    351. max: 15,
    352. startX: 0,
    353. startY: 0,
    354. perspective: 1000,
    355. easing: "cubic-bezier(.03,.98,.52,.99)",
    356. scale: 1,
    357. speed: 300,
    358. transition: true,
    359. axis: null,
    360. glare: false,
    361. "max-glare": 1,
    362. "glare-prerender": false,
    363. "full-page-listening": false,
    364. "mouse-event-element": null,
    365. reset: true,
    366. gyroscope: true,
    367. gyroscopeMinAngleX: -45,
    368. gyroscopeMaxAngleX: 45,
    369. gyroscopeMinAngleY: -45,
    370. gyroscopeMaxAngleY: 45,
    371. gyroscopeSamples: 10
    372. };
    373. let newSettings = {};
    374. for (var property in defaultSettings) {
    375. if (property in settings) {
    376. newSettings[property] = settings[property];
    377. } else if (this.element.hasAttribute("data-tilt-" + property)) {
    378. let attribute = this.element.getAttribute("data-tilt-" + property);
    379. try {
    380. newSettings[property] = JSON.parse(attribute);
    381. } catch (e) {
    382. newSettings[property] = attribute;
    383. }
    384. } else {
    385. newSettings[property] = defaultSettings[property];
    386. }
    387. }
    388. return newSettings;
    389. }
    390. static init (elements, settings) {
    391. if (elements instanceof Node) {
    392. elements = [elements];
    393. }
    394. if (elements instanceof NodeList) {
    395. elements = [].slice.call(elements);
    396. }
    397. if (!(elements instanceof Array)) {
    398. return;
    399. }
    400. elements.forEach((element) => {
    401. if (!("vanillaTilt" in element)) {
    402. element.vanillaTilt = new VanillaTilt(element, settings);
    403. }
    404. });
    405. }
    406. }
    407. if (typeof document !== "undefined") {
    408. /* expose the class to window */
    409. window.VanillaTilt = VanillaTilt;
    410. /**
    411. * Auto load
    412. */
    413. VanillaTilt.init(document.querySelectorAll("[data-tilt]"));
    414. }
    415. return VanillaTilt;
    416. }());

    使用:

    1. VanillaTilt.init(document.querySelectorAll('.publicize-item'), {
    2. max: 15, //最大倾斜度数
    3. speed: 400, //倾斜转换的速度
    4. glare: true, //是否开启眩光效果
    5. 'max-glare': 1, //最大眩光的不透明度
    6. scale: 1.05 //指定2D旋转的缩放
    7. });

    配置项

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/93877
推荐阅读
相关标签
  

闽ICP备14008679号