为什么在使用SVG效果滚动时过热

问题描述 投票:0回答:1

我在页面部分创建了SVG模糊效果。您可以在下面的代码段中看到。但是,当我滚动几次时,我的CPU过载并使笔记本电脑过热。我检查复杂的动画网站没有这个问题。我的问题是什么?我的代码有问题吗?

$(window).on('load', function() {
  $('.blurred-bg').each(function(index, value) {
    var filterName = $(this).attr('id') + 'filtering';
    $(this).prepend(
      '<svg class="svgs" xmlns="http://www.w3.org/2000/svg" version="1.1" height="0"><filter id="' + filterName + '"><feGaussianBlur result="blur"></feGaussianBlur><feMorphology in="blur" operator="dilate" radius="15" result="expanded"/><feMerge><feMergeNode in="expanded"/><feMergeNode in="blur"/></feMerge></filter></svg>'
    );
  });

  $(window).scroll(function(e) {
    var distanceScrolled = $(this).scrollTop();
    $('.blurred-bg').each(function(index, value) {
      var distanceElementTop = ($(this).offset().top);
      if (distanceScrolled < distanceElementTop) {
        $(('svg.svgs filter feGaussianBlur'), this)[0].setAttribute("stdDeviation", '0');
      } else if (distanceScrolled > distanceElementTop) {
        var elmHeight = $(this).height();
        var sub = elmHeight / 10;
        var result = ((distanceScrolled - distanceElementTop) / sub);
        if (result >= 0 && result <= 10) {
          $(('svg.svgs filter feGaussianBlur'), this)[0].setAttribute("stdDeviation", result);
        }
      }
    });
  });
});
section {
  position: relative;
  width: 100%;
  height: 100vh;
  background-size: cover;
  background-attachment: fixed;
  background-repeat: no-repeat;
  overflow-x: hidden;
  overflow-y: auto;
}

section:before {
  background: inherit;
  bottom: 0;
  content: '';
  left: 0;
  position: absolute;
  right: 0;
  top: 0;
}

#first {
  background-image: url('https://freephotos.cc/storage/path/1Sujr0vCiT0cQpjbMgmdzAIjtdfEq2lF3bq4U1oo.jpeg');
}

#first:before {
  -webkit-filter: url(#firstfiltering);
  filter: url(#firstfiltering);
}

#two {
  background-image: url('https://freephotos.cc/storage/path/c1haICnHGYIyRK2juLs36iEBoBiJMOarzSQ9CKRv.jpeg');
}

#two:before {
  -webkit-filter: url(#twofiltering);
  filter: url(#twofiltering);
}

#three {
  background-image: url('https://freephotos.cc/storage/path/OpgzqCRPTnxQ5z22gNvNgiF7ZSTzNyPXtXKwVwS4.jpeg');
}

#three:before {
  -webkit-filter: url(#threefiltering);
  filter: url(#threefiltering);
}

.svgs,
.svg-section {
  position: absolute;
  width: 0;
  height: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section id="first" class="blurred-bg"></section>
<section id="two" class="blurred-bg"></section>
<section id="three" class="blurred-bg"></section>

https://codepen.io/mehrdadam/pen/NyexLa

更新:

我测试这个没有SVG过滤器并删除jQuery并设置模糊过滤器的部分。我的CPU因模糊部分而超载!

javascript jquery overloading vertical-scrolling svg-filters
1个回答
0
投票

不断重新计算的模糊是非常CPU密集的。更好的方法是在原始图像上叠加高度模糊,透明的图像副本,并在向下滚动时逐渐增加其不透明度。

© www.soinside.com 2019 - 2024. All rights reserved.