Tuesday, August 25, 2015

Creating a tiltshift effect with the -webkit-backdrop-filter

When I first heard about the new CSS filters being added to webkit and Safari (especially the backdrop-filter) I immediately wanted to see if I could create a tilt shift effect. For those that don't know, tilt shift photography is a technique that can simulate a miniature scene by using lens tilt for selective focus. There are already Javascript plugins such as tiltShift.js that can create this effect but I wanted to go for a pure CSS approach.

Note: this only works in Webkit nightly at the moment. Hopefully other browser vendors follow.

My approach uses three elements, an image to act as a mask, a div for the backdrop-filter and the image that is being affected.



radialMask.pngnyc.png









I also decided to animate the position of the mask so that the effect could be seen better. Here is the code and an animated gif of the effect as seen in Webkit:

    <style>
      img {
        position: absolute;
        top: 0;
        left: 0;
      }
      .mask {
        animation-duration: 4s;
        animation-name: moveBlur;
        animation-iteration-count: infinite;
        animation-direction: alternate;
        -webkit-animation-duration: 4s;
        -webkit-animation-name: moveBlur;
        -webkit-animation-iteration-count: infinite;
        -webkit-animation-direction: alternate;
        -webkit-mask-image: url(radialMask.png);
        -webkit-mask-position-x: 50%;
        -webkit-mask-position-y: 5%;
        -webkit-mask-repeat: no-repeat;
        z-index: 200;
      }
      .blurFilter {
        position: absolute;
        top: 0;
        left: 0;
        width: 550px;
        height: 412px;
        background-color: rgba(89, 124, 135, 0.3);
        -webkit-backdrop-filter: blur(2px);
        backdrop-filter: blur(2px);
        z-index: 100;
      }
      @keyframes moveBlur {
        from{
          -webkit-mask-position-y: 5%;
        }
        to {
          -webkit-mask-position-y: 100%;
        }
        @-webkit-keyframes moveBlur {
          from{
            -webkit-mask-position-y: 5%;
          }
          to {
            -webkit-mask-position-y: 100%;
          }
      }
    </style>
  </head>
  <body>
    <img src="nyc.png" class="mask" />
    <div class="blurFilter"></div>
    <img src="nyc.png" />
  </body>