Quantcast
Viewing all articles
Browse latest Browse all 10

Clipping paths

Clipping an area is just like normal canvas shape it helps in masking the unnecessary parts of the shapes . The image towards the right showcases a masked image . The star which is red in color will be used to clip through the surface .what ever the area that falls outside this clipping area will not be displayed.Image may be NSFW.
Clik here to view.

In this post we will discuss about the clipping paths using the canvas clip() method.

clip()
This canvas elements – clip() method can be used to create new clipping path .By default this canvas element has a
clipping path that has the same size as that of the canvas .

A clip example

In the below example a circular clip is used to reduce the area of the stars that is spread over the picture .

Image may be NSFW.
Clik here to view.

Initially a black rectangle in the background is drawn using the canvas draw() element using the origin to the center . Below this a circular clipping path is drawn using an arc .If we wanted to keep the original clipping path we should save the canvas state before we create a new one.

function draw() {
  var ctx = document.getElementById('canvas').getContext('2d');
  ctx.fillRect(0,0,150,150);
  ctx.translate(75,75);

  // Create a circular clipping path
  ctx.beginPath();
  ctx.arc(0,0,60,0,Math.PI*2,true);
  ctx.clip();

  // draw background
  var lingrad = ctx.createLinearGradient(0,-75,0,75);
  lingrad.addColorStop(0, '#232256');
  lingrad.addColorStop(1, '#143778');

  ctx.fillStyle = lingrad;
  ctx.fillRect(-75,-75,150,150);

  // draw stars
  for (var j=1;j<50;j++){
    ctx.save();
    ctx.fillStyle = '#fff';
    ctx.translate(75-Math.floor(Math.random()*150),
                  75-Math.floor(Math.random()*150));
    drawStar(ctx,Math.floor(Math.random()*4)+2);
    ctx.restore();
  }

}
function drawStar(ctx,r){
  ctx.save();
  ctx.beginPath()
  ctx.moveTo(r,0);
  for (var i=0;i<9;i++){
    ctx.rotate(Math.PI/5);
    if(i%2 == 0) {
      ctx.lineTo((r/0.525731)*0.200811,0);
    } else {
      ctx.lineTo(r,0);
    }
  }
  ctx.closePath();
  ctx.fill();
  ctx.restore();
}

Image may be NSFW.
Clik here to view.
DZone
Image may be NSFW.
Clik here to view.
StumbleUpon
Image may be NSFW.
Clik here to view.
Digg
Image may be NSFW.
Clik here to view.
Share


Viewing all articles
Browse latest Browse all 10

Trending Articles