显示标签为“canvas”的博文。显示所有博文
显示标签为“canvas”的博文。显示所有博文

2015年10月4日星期日

UNBLUR BACKGROUND (PART 3)

Fading effect

So the fading effect would be using a loop of timed-out call to simulate. It will be something like this...

var painter = $('<canvas>').attr('width', $(window).width()).attr('height', $(window).height())[0], 
    pctx = painter.getContext('2d'), ctx = $('#canvas2')[0].getContext('2d'), img= $('img')[0];
for(var i = i; i <= 10; i++){
  (function(i){
    setTimeout(function(){
        pctx.strokeStyle = "rgba(0,0,0,"+(1 - i / 10)+")";
        pctx.beginPath();
        pctx.moveTo(760, 20);
        pctx.lineTo(760, 100);
        pctx.stroke();
        ctx.drawImage(img, 0, 0, img.width, img.height);
        ctx.globalCompositeOperation = "destination-in";
        ctx.drawImage(painter, 0, 0);
        ctx.globalCompositeOperation = "source-over";
 },i * 200);
  })(i);
}

But I cannot make it directly work with mousemove event, because it fires for every pixel mouse move which is very costly and inefficient. And also for every line it draws, it draws also one image and one canvas as well, which is also very expensive.

This is what I'm going to do. Firstly, the event, instead of directly drawing, it just records the current mouse coordinate and the time stamp and trigger one recursive function if it's not started. And then the recursive function, which will constantly run once in a short while till no more event occurs, it contains the logic of drawing, coordinate collection adding and removal and the indicator that decide whether it can be triggered. Finally, I need a collection that stores coordinates so that I can draw all of them in the painter and copy the painter to the main canvas.

Collect the coordinates

The first thing is, I'm going to need an array to store coordinate objects.

var points = [];

Handle the mousemove event

Firstly I instantiate several global variables so I can read in the recursive function. And in the event handler, I record the coordinate and time stamp and trigger the recursive function if it’s not started yet.

var x, y, eventTimestamp, isContinue;
$(document).on('mousemove', function(e){
  x = e.clientX, y = e.clientY, eventTimestamp = Date.now;
  if(!isContinue) draw();
});

The recursive function

This function does basically three things.

  • It adds and removes coordinates of the collection.
  • It checks and decides whether it continues and can be triggered by the event handler.
  • It draws all lines using adjacent coordinates and put it to the main canvas.

This function makes a delayed call to itself if mousemove event keeps firing. And when it executes it adds the new coordinate object to the collection. I can use this for the fading effect. So I put time stamps in coordinate objects and compare them with the newest one to decide the opacity value. By doing this, it draws lines with different fading effects and refreshes the canvas every time it executes. That's how the amination works.

function draw(){
  var currentTimestamp = Date.now, newPoint = {x: x, y: y, t: currentTimestamp};
  
  //check if to continue
  isContinue = currentTimestamp - eventTimestamp < 500;
  //add new coordinate
  if(isContinue){
 points.unshift(newPoint);
  }
  //remove faded out coordinates
  for(var i = 0; i < points.length;){
 currentTimestamp - points[i].t > 1000 ? points.splice(i, points.length) : i++;
  }
  //recursive call
  if(points.length){
 setTimeout(draw, 20);
  }
  
  var painter = $('<canvas>').attr('width', $(window).width()).attr('height', $(window).height())[0], pctx = painter.getContext('2d');
  //clear painter, ready to draw
  pctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
  //draw all lines in the collection
  for (var i = 1; i < points.length; i++) {
 pctx.strokeStyle = "rgba(0,0,0," + Math.max(1-(currentTimestamp-points[i].t)/1000, 0) + ")";
 //umcomment this line to get dynamic line width
 //pctx.lineWidth = 25+75*Math.max(1-Math.sqrt(Math.pow(points[i].x-points[i-1].x,2)+Math.pow(points[i].y-points[i-1].y,2))/50,0);
 pctx.lineWidth = 50;
 pctx.beginPath();
 pctx.moveTo(points[i - 1].x, points[i - 1].y);
 pctx.lineTo(points[i].x, points[i].y);
 pctx.stroke();
  }
  var ctx = $('canvas')[0].getContext('2d'), img= $('img')[0];
  //copy-paste 
  ctx.drawImage(img, 0, 0, img.width, img.height);
  ctx.globalCompositeOperation = "destination-in";
  ctx.drawImage(painter, 0, 0);
  ctx.globalCompositeOperation = "source-over";
}

Handle resize

The background will automatically re-adjust to adopt the new width or height. So the image and canvases are also need to be taken care of.

$(window).on('resize', function(){
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);
  }
  $('canvas').attr('width', windowWidth).attr('height', windowHeight);
});

So that's the all of it. I put the demo effect on the background. Feel free to try.



UNBLUR BACKGROUND (PART 1)

UNBLUR BACKGROUND (PART 2)

2015年9月30日星期三

UNBLUR BACKGROUND (PART 2)

Start to draw

The basic idea is to draw lines with blurring effect from the last coordinate to the current coordinate whenever mouse moved and make it fade over time to zero. Here I want to draw line with brash effect and blur effect. And then to make it fade, I simply manipulate the opacity a bit. So let's see what comes out.

var ctx = $('canvas')[0].getContext('2d');
ctx.lineCap = "round";
ctx.shadowColor = "#000";
ctx.lineWidth = 30;
ctx.shadowBlur = 30;
for(var i=0; i<=10;i++){
 ctx.strokeStyle = "rgba(0,0,0,"+(1-i/10)+")";
 ctx.beginPath();
 ctx.moveTo(i*70+50, 20);
 ctx.lineTo(i*70+50, 100);
 ctx.stroke();
}

Well, to draw lines with a single color is easy. What about copy some photo parts and fill them to those lines? There are two options, compositing and clipping. Initially I thought clipping was more promising because it was simpler and more straightforward. Soon after that I began to have problems with implementing blurring and fading effects. And most importantly the browser started to lag when those was added. So I decided to try the other approach.

Global Composite Operation

By definition, the canvas 2D rendering context globalCompositeOperation property of the Canvas 2D API sets the type of compositing operation to apply when drawing new shapes. And the type "destination-in" keeps the existing canvas content where both the new shape and existing canvas content overlap. Everything else is made transparent. So I can draw a line and paste the image to achieve the goal. See the effect.

But wait, it can only draw something in the overlap zone. to make trace of mouse move I'm definitely going to draw lots of lines not just in a narrowing area. Ideally, it would be great I can draw whole trace in somewhere else and paste it into canvas. It took me a while to figure out that it could actually copy the drawing from one canvas and paste it to another one. So the idea came out. Draw the whole trace in a temporary canvas and then paste the drawing to the main canvas. And I found out that this temp canvas doesn't have to be inside the body. It just needs to be instantiate properly with exactly same width and height.

var painter = $('<canvas>').attr('width', $(window).width()).attr('height', $(window).height())[0], 
    pctx = painter.getContext('2d');

pctx.lineCap = "round";
pctx.shadowColor = "#000";
pctx.lineWidth = 30;
pctx.shadowBlur = 30;

for(var i = 0; i <= 10; i++){
 pctx.strokeStyle = "rgba(0,0,0," + (1 - i / 10) + ")";
 pctx.beginPath();
 pctx.moveTo(i * 70 + 50, 20);
 pctx.lineTo(i * 70 + 50, 100);
 pctx.stroke();
}

var ctx = $('canvas')[0].getContext('2d'), img= $('#imgtarget')[0];

ctx.drawImage(img, 0, 0, img.width, img.height);
ctx.globalCompositeOperation = "destination-in";
ctx.drawImage(painter, 0, 0);
ctx.globalCompositeOperation = "source-over";

So I've got the method to draw. The next step would be to use it to handle the mousemove event. But handling the event was far more complicated than I thought. I will break it down next time.



UNBLUR BACKGROUND (PART 1)

UNBLUR BACKGROUND (PART 3)

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)