a blog for those who code

Tuesday, 20 October 2015

Drawing and Cropping an Image using HTML5 Canvas Element

In this post we will be discussing about drawing and cropping an image using canvas element in HTML5. For drawing an image we have to first load an image and draw it on the canvas and for cropping an image we have to crop out a section of an image and then draw the result onto the canvas. As per canvas definition, it provides scripts with a resolution-dependent bitmap canvas, which can be used for rendering graphs, game graphics, art, or other visual images on the fly.


Draw an Image

var image = new Image();
image.onload = function() {
  var x = canvas.width / 2 - this.width / 2;
  var y = canvas.height / 2 - this.height / 2;
  context.drawImage(this, x, y);
};
image.src = http://3.bp.blogspot.com/-vJcblLR5n7g/U7Vh52-vssI/AAAAAAAAACA/M2EcY7husXc/s1600/nodejslogo.jpg

Check at : http://codepen.io/codingdefined/pen/vNpJbo

In the above code at first we have created an image object using new Image(). Then we set the onload property of the image object where we drew the image using context.drawImage(). After that we will set the source of the image.

Crop an Image

var image = new Image();
image.onload = function() {
  var sourceX = 100; var sourceY = 50;
  var sourceWidth = 395; var sourceHeight = 128;
  
  var destWidth = sourceWidth; var destHeight = sourceHeight;
  var x = canvas.width / 2 - destWidth / 2; var y = canvas.height / 2 - destHeight / 2;
  context.drawImage(this, sourceX, sourceY, sourceWidth, sourceHeight, x, y, destWidth, destHeight);
};
image.src = 'http://3.bp.blogspot.com/-vJcblLR5n7g/U7Vh52-vssI/AAAAAAAAACA/M2EcY7husXc/s1600/nodejslogo.jpg';

Check at : http://codepen.io/codingdefined/pen/MarEeG

In the above code at first we have created an image using new Image(). Then we set the onload property of the image object where we drew the image using context.drawImage(). We have to sent 9 parameters to drawImage() function if we wanted to crop an image.

The sourceX and sourceY refer to the top-left corner of the cropped region in the source image. sourceWidth and sourceHeight refer to the width and height of the cropped image from the source. x and y refer to the position of the cropped image on the canvas and destWidth and destHeight refer to the width and height of the resulting cropped image.

Please Like and Share the CodingDefined Blog, if you find it interesting and helpful.

No comments:

Post a Comment