2015年9月27日星期日

UNBLUR BACKGROUND (PART 1)

Recently I've found a very interesting animation effect from this website, which can unblur the blurred background and leave a disappearing track on the screen. I want to make one myself but I couldn't find any library can do something like that. So I tried to build one from scratch. So the basic idea is to use a blurred image as background image and use HTML5 <canvas> tag to draw a small dot with the original image on the location whenever mouse move.

Prepare background

Frist thing I will need two same images, one blur and one not. And then set up the blurred image as background and make it not repeat, cover the whole screen and not moving with scroll. Here background-attachment:fixed makes it fixed with regard to the viewport, and background-size:cover makes it always cover the whole screen and keep the image aspect ratio.

body{
  background: url('images/background-blur.jpg') no-repeat 0 0 fixed;
  background-size: cover;
}

Prepare image

And then set up the image to draw. This image will basically need to be kept invisible. But I cannot use display:none here because I'm going to need to read its width and height in the future. Most importantly, the image needs to be adjust its width and height to be identical with the background.

<div style="position:absolute;width:0;height:0;overflow:hidden;">
  <img src="background.jpg" alt="" / >
</div>
<script>
  var img = $('img')[0];
  var windowHeight = $(window).height(), windowWidth = $(window).width(), windowRate = windowWidth/windowHeight;
  var imgHeight = img.naturalHeight, imgWidth = img.naturalWidth, imgRate = imgWidth/imgHeight;

  if(windowRate>=imgRate){
    $(img).attr('height', (imgHeight/imgWidth*windowWidth)).attr('width', windowWidth);
  }else{
    $(img).attr('width', (imgWidth/imgHeight*windowHeight)).attr('height', windowHeight);
  }
</script>

Prepare canvas

I also need create a <canvas> element, make it cover the whole screen and set the position to fixed. Here I got a problem. It is a bit difficult to set height. And I have to use a piece of javascript to make it work properly.

<script>
  $('body').append(
    $('<canvas style="position:fixed;top:0;left:0;z-index:-1;"></canvas>')
   .attr('width', $(window).width()).attr('height', $(window).height())
  );
</script>

I'm going to have to split this article to several parts. Next time I'm going to explain how it works between image and canvas.



UNBLUR BACKGROUND (PART 2)

UNBLUR BACKGROUND (PART 3)

没有评论:

发表评论