HTML5 > Canvas

Image masking on Canvas in HTML5

How to create the image masking using canvas HTML5


Image Masking

Image Masking is used to create the shape of the image by using properties of the moveto(), lineto(), arcto(), clip(), drawimage(), restore().

 <h2 style=" color:blue;">Image masking</h2>
    <canvas id="mycanvas" width="200" height="150"></canvas>
   <script>
        var canvas = document.getElementById("mycanvas");
        var ctx = canvas.getContext('2d');

        var img = document.createElement('IMG');
        img.onload = function () {

            ctx.save();
            ctx.beginPath();
            ctx.moveTo(20, 10);
            ctx.lineTo(100, 30);
            ctx.lineTo(180, 10);
            ctx.lineTo(200, 60);
            ctx.arcTo(180, 70, 120, 0, 10);
            ctx.lineTo(200, 180);
            ctx.lineTo(100, 150);
            ctx.lineTo(70, 180);
            ctx.lineTo(20, 130);
            ctx.lineTo(50, 70);
            ctx.closePath();
            ctx.clip();
            ctx.drawImage(img, 0, 0);
            ctx.restore();
        }
        img.src = "http://techfunda.com/HTPictures/Generics/5-635898849972807270.JPG";
    </script>

In the above code snippet we have defined the image masking. we are having the canvas element as width as mycanvas with the width of 200 and height as 150,  

var canvas = document.getElementById("mycanvas"); - it defines the the id of the canvas as mycanvas

var ctx = canvas.getContext('2d');- It defines the context to the canvas element

var img = document.createElement('IMG'); - it defines the image and we are giving the id of the image 

img.onload = function ()  - we are giving the function as image onload and in the nextline we are giving the values of the image in the function 

In the last line we are giving the image source as img.src of the bottle.

output

   

 Views: 8678 | Post Order: 39



Write for us






Hosting Recommendations