滚动时的运动模糊效果



我试图在滚动时将运动模糊效果应用于HTMLdiv。为了做到这一点,我需要每隔1/5秒克隆一次每个div,并在滚动时保持其在页面上的位置固定。我还需要每1/5秒降低每个div克隆的不透明度,并确保页面上一次只有5个div克隆(这样几秒钟后页面上就会有数百个div克隆)。使用这种方法可以在JavaScript中创建运动模糊效果吗?

<div id = "blurOnScroll">
Create the illusion of a motion blur by creating clones of this div every 1/5 of a second, reducing the opacity of each clone every 1/5 of a second, and remove each clone as soon as it has completely faded away.
</div>
<script type = "text/javascript">
    function motionBlurEffect(){
        //create the illusion of a motion blur effect, as described above.
    }
</script>

此实现使用SVG高斯模糊过滤器。模糊的强度基于滚动的速度

var blurFilter = document.getElementById('blur-kernel');
var html = $('html');
var prevPos = $(window).scrollTop();
var prevTime = Date.now();
var speed = 0;
var cheat = 0;
function blur() {
  cheat = 1 - cheat; // alternates between 0 and 1; used to force browser repaint by setting CSS
  let newPos = $(window).scrollTop();
  let newTime = Date.now()
  // distance over time times milliseconds per frame
  velocity = (newPos - prevPos) / Math.max(1, newTime - prevTime) * 1000 / 60;
  
  prevPos = newPos;
  prevTime = newTime;
  
  const STRENGTH = 1;
  blurSize = Math.max(0, Math.abs(velocity) / 2 * STRENGTH - 0.5);
  blurFilter.setStdDeviation(0, Math.floor(blurSize));
  blurFilter.setAttribute('stdDeviation', '0,' + blurSize);
  // forces browser repaint
  html.css('width', cheat + 'px');
  
  requestAnimationFrame(blur);
}
requestAnimationFrame(blur);
html {
  filter: url(#blur);
  -webkit-filter: url(#blur);
  will-change: filter, -webkit-filter;
  transform: translateZ(0);
  font: 16px sans-serif;
  line-height: 1.5;
}
body, img {
  /* setting the width of the body makes the
  html element's force-repaint "cheat" have no visible effect */
  width: calc(100vw - 20px); /* minus scrollbar */
  margin: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eget tincidunt ipsum. Nullam metus mauris, scelerisque vel accumsan at, dapibus non odio. Cras volutpat malesuada tempus. Pellentesque vehicula posuere dolor et aliquet. Proin laoreet nisl sapien, ut congue neque placerat at. In ac nulla nec erat pretium egestas id ut orci. Vestibulum nec ultrices diam, sed efficitur ligula. Maecenas elementum molestie diam, vel mattis velit. Sed eu dignissim nibh, quis sollicitudin dolor. Praesent interdum pharetra aliquam. Maecenas mi est, semper nec dui euismod, semper interdum sem. Vestibulum sed porttitor purus. Ut convallis non urna non blandit. Quisque pharetra dolor ac ex dictum ultrices. Vestibulum cursus hendrerit elit. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.
</p>
<img src='https://res.cloudinary.com/demo/image/upload/w_250,h_250,c_mfit/w_700/sample.jpg'>
<p>
Praesent mi nisl, dictum nec velit tincidunt, vestibulum congue purus. Nam venenatis elit lectus, quis fringilla felis dictum sed. Etiam ac lacus a neque lobortis rhoncus at vitae felis. In dapibus massa massa. Integer semper egestas interdum. Praesent augue magna, ultrices at consectetur eget, semper sit amet sapien. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Quisque sollicitudin libero tortor, at gravida justo suscipit et. Maecenas euismod tellus eget lectus sollicitudin, nec consequat mauris porta. Aliquam vitae dolor ut ante commodo volutpat non sed leo. Donec malesuada justo tempus enim aliquet cursus. Pellentesque magna lectus, rhoncus ac porttitor at, congue vitae eros.
</p>
<p>
Proin ultricies dignissim arcu. Maecenas felis nunc, convallis non turpis at, laoreet dictum velit. Proin euismod libero ut orci commodo, in consequat orci fringilla. Donec ac congue mauris, lacinia mollis risus. Maecenas lorem diam, pulvinar quis est non, ornare cursus libero. Quisque ut magna sed arcu hendrerit facilisis eget vitae risus. In gravida nunc nec arcu tincidunt finibus. Nam sem ligula, vulputate in lorem ut, lobortis feugiat purus. Etiam placerat arcu efficitur risus pharetra eleifend. Nunc consectetur urna quis sapien placerat molestie. Vestibulum commodo elit nec facilisis varius. Ut ut posuere nisl, vitae pharetra enim. Aliquam molestie viverra venenatis.
</p>
<img src='https://photographycourse.net/wp-content/uploads/2014/11/Landscape-Photography-steps.jpg'>
<p>
Quisque tempus, sem et malesuada ornare, orci leo pulvinar nisi, laoreet vestibulum augue sem vitae nisl. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Morbi quis commodo lorem. Sed ac scelerisque mauris, in lobortis ligula. Curabitur vestibulum blandit auctor. Aenean viverra turpis in dui tincidunt, vitae auctor quam faucibus. Sed id risus cursus, vehicula lorem at, tincidunt mi. Aenean maximus porttitor magna cursus interdum. Etiam sit amet mattis quam. Fusce sodales sodales porta. In hendrerit, velit eget tempus pretium, sapien tortor rutrum enim, eget aliquet libero velit et libero. Aliquam a consequat sem. Integer feugiat ut quam eu finibus. Sed rhoncus eleifend viverra. Mauris at viverra nulla, sit amet ultrices diam.
</p>
<p>
In sagittis nisi quis mi tristique mollis. Sed vulputate orci quis leo commodo, eu auctor orci tincidunt. Nullam eget posuere felis, in ultricies nibh. Nunc congue lorem sed elit fringilla lacinia. Vivamus ac ante tempor, ultricies ante nec, volutpat eros. Aenean laoreet justo imperdiet metus placerat accumsan. Quisque odio nibh, venenatis sit amet dignissim ut, tempor ultrices libero.
</p>
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" class="filters">
  <defs>
    <filter id="blur">
      <feGaussianBlur id="blur-kernel" in="SourceGraphic" edgeMode='duplicate' stdDeviation="0,0" />
    </filter>
  </defs>
</svg>

我正在MacBook Pro上测试它,Chrome是唯一一款运动模糊效果流畅的浏览器。我认为,由于渲染技术的不同,它在Safari和Firefox中非常滞后。

我在Stackoverflow上找到了这篇文章:

这种模糊效果是如何在javascript中实现的?

$('img').on('mouseenter', function () {
        var $theClone = $(this).clone().css({ opacity : 0.5, position : 'absolute', top : 0 });
        $(this).parent().append($theClone);
        $theClone.animate({ left : 10 }, 500).on('mouseleave', function () {
            $(this).stop().fadeOut(250, function () {
                $(this).remove();
            });
        });      
    });​

或者这个功能:

  function addParallaxScrolling() {
        if (!$("bgImageTop")) {
            return
        }
        if (window.orientation == undefined && !Browser.firefox) {
            var body = document.getElement("body"),
                headerimage = $("bgImageTop"),
                headergrad = $("bgGradientTop");
            window.addEvent("scroll", function windowScrollEvent() {
                body.setStyle("background-position", "0px " + (this.getScroll().y / 4) + "px");
                headerimage.setStyle("top", this.getScroll().y / 4 + "px");
                headergrad.setStyle("top", headerimage.getStyle("top").toInt() + headerimage.getStyle("height").toInt() + "px")
            })
        }
    }

希望我能帮助你。

相关内容

  • 没有找到相关文章

最新更新