How to crop extra canvas spaces?

49 views Asked by At

My first concern was to fit image <= height of canvas and to that I have used following code..

       var canvas = ctx.canvas ;
       var hRatio = canvas.width  / img.width    ;
       var vRatio =  canvas.height / img.height  ;
       var ratio  = Math.min ( hRatio, vRatio );
       var centerShift_x = ( canvas.width - img.width*ratio ) / 2;
       var centerShift_y = ( canvas.height - img.height*ratio ) / 2;  
       ctx.clearRect(0,0,canvas.width, canvas.height);
       ctx.drawImage(img, 0,0, img.width, img.height,
                          centerShift_x,centerShift_y,img.width*ratio, img.height*ratio);  

The above code is working as I wanted ,but when I download the image, the image also contains spaces in both side if the width < height and spaces in bottom at top if the width > height.

Example

Actual Image

   _________
  |  (-.-)  |
  |   \|/   |
  |    |    |
  |   / \   |
  |_________|

On saving, the image looks something like this

   _______________
  |     (-.-)     |
  |      \|/      |
  |       |       |
  |      / \      |
  |_______________|

So on saving I don't to save image along with canvas spaces.. Please Help..

0

There are 0 answers