首页 > 解决方案 > 使用 requestAnimationFrame 启动和停止在 Barba.js 中运行 three.js 的函数?

问题描述

我的主页正在运行 three.js,我正在使用 barba.js 来使用 ajax 来实现页面之间更平滑的转换。问题是,在我来回离开主页并返回几次后,我的网站开始运行非常缓慢。我正在想办法解决这个问题,我认为我有一个使用 barba.js 视图和 requestAnimationFrame 的方法,但我认为它没有足够的帮助。有没有人更好地了解如何销毁或停止执行我的 three.js 函数?

barbaMain.js

document.addEventListener("DOMContentLoaded", function () {
  var lastElementClicked;
  let animationLoop = null

  const SingleNews = Barba.BaseView.extend({
    namespace: 'single-news',
    onEnterCompleted: function () {
        animationLoop = requestAnimationFrame( doThree )
    },

    onLeave: function() {
      cancelAnimationFrame(animationLoop)
    },

  });

  SingleNews.init()

Barba.Pjax.start();






  Barba.Dispatcher.on('linkClicked', function(el) {
    lastElementClicked = el;
  });
  var FadeTransition = Barba.BaseTransition.extend({
    start: function() {

      Promise
        .all([this.newContainerLoading, this.fadeOut()])
        .then(this.fadeIn.bind(this));
    },

    fadeOut: function() {

      return $(this.oldContainer).animate({
          opacity: 0
        }, 400, function() {} ).promise()
    },

    fadeIn: function() {

      var _this = this;
      var $el = $(this.newContainer);

      $(this.oldContainer).hide();

      $el.css({
        visibility: 'visible',
        opacity: 0
      });

      $el.animate({
        opacity: 1
      }, 400, function() {

        _this.done();

      });
    }
  });


  Barba.Pjax.getTransition = function() {

      return FadeTransition;
  };
})

HTML

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>Jacob Truax Portfolio</title>
  <link rel="stylesheet" href="normalize.css">
  <link rel="stylesheet" href="canvas-fix">
  <link rel="stylesheet" href="style.css">

  <link href="https://fonts.googleapis.com/css?family=IBM+Plex+Mono" rel="stylesheet">
  <script src="three.min.js"></script>
  <script src="portfolio.js"></script>
  <script src="jquery-3.3.1.min.js"></script>
  <script src="barba.js"></script>
  <script src="barbaMain.js"></script>

</head>

<body>

<div id="barba-wrapper">
  <div class="barba-container" data-namespace="single-news">
  <header>
  <a class="home" href="#">Jacob Truax</a>
  <a class="contact" href="info.html">Info</a>
  <a class="info" href="#">Work</a>
  </header>

<section class="three"></section>
</div>
</div>
</body>

三个.js函数都在这个里面:

const doThree = function () {}

标签: javascriptthree.jspjax

解决方案


推荐阅读