Canvas How to - Crop and image








Question

We would like to know how to crop and image.

Answer


<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
    function init(){<!--  www. j  av  a2  s .com-->
        canvas=document.getElementById('canvas1');    //get the canvas element from HTML
        ctx = canvas.getContext("2d");
        var img1 = new Image();
        img1.onload = function(){
            var w = img1.width
            var h = img1.height
            ctx.drawImage(img1,0,0);
            // Create a circular clipping path 
            ctx.translate(w / 2,  1.5 * h);       
            ctx.beginPath();
            ctx.arc(0,0,50,0,Math.PI*2,true);
            ctx.clip();
            ctx.drawImage(img1,-w / 2,-80);
        }
        img1.src = "http://www.java2s.com/style/download.png";
    }
</script>
</head>
<body onload="init();" bgcolor="yellow">
  <canvas id="canvas1" width="1000" height="1000"></canvas>
</body>
</html>

The code above is rendered as follows: