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 = https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhydXlQESwstWvPoSpdd8LOEkNslqVpUaGoP-xjG4Xa0InB-jKDDr4ZrdEE3jbCEc4yL70x0V-Tt4pf5NS9FbfPANCOf79f50h8OfamqWTttNECm29dGcQ9jR_FOrZlnoAhzMI7aRbmB018/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 = 'https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhydXlQESwstWvPoSpdd8LOEkNslqVpUaGoP-xjG4Xa0InB-jKDDr4ZrdEE3jbCEc4yL70x0V-Tt4pf5NS9FbfPANCOf79f50h8OfamqWTttNECm29dGcQ9jR_FOrZlnoAhzMI7aRbmB018/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