To crop an image using HTML canvas, if the image is from the local domain then it's easy.
However, if the image is from a different domain, CORS security errors will occur: http://code.google.com/p/html5security/wiki/CrossOriginRequestSecurity
If necessary, you can also adjust the scale while cropping.
Below is an example code snippet that demonstrates how to use the drawImage
function of canvas to crop an image:
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var img=new Image();
img.onload=function(){
crop();
}
img.src=document.getElementById("source").src;
function crop(){
// This crops a 105x105px area from the image at x=149/y=4
// and pastes it onto the canvas
ctx.drawImage(img,149,4,105,105,0,0,105,105);
// Sets the cropped image as the source for the 'cropped' image element
document.getElementById("cropped").src=canvas.toDataURL();
}
}); // end $(function(){});
</script>
</head>
<body>
<img id="source" width=400 height=234 src="localImage.png">
<img id="cropped" width=105 height=105>
<canvas id="canvas" width=105 height=105></canvas>
</body>
</html>