To crop an image, use drawImage() method with nine arguments:
It has the following format:
context.drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh);
<!DOCTYPE html> <html> <head> <title>Manipulating images and video</title> <meta charset="utf-8"> //from w ww.j ava 2s . c o m <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { let canvas = $("#myCanvas"); let context = canvas.get(0).getContext("2d"); let image = new Image(); image.src = "http://java2s.com/style/demo/jet2.png"; $(image).load(function() { context.drawImage(image, 0, 0, 250, 250, 0, 0, 250, 250); }); }); </script> </head> <body> <canvas id="myCanvas" width="500" height="500"> <!-- Insert fallback content here --> </canvas> </body> </html>
We can resize the cropped image as you draw in onto the canvas, like so:
context.drawImage(image, 0, 0, 250, 250, 0, 0, 500, 500);