HTML Canvas Image draw image to position

Introduction

To draw an image, we first need to create an image object using new Image().

We set the onload property of the image object before defining the source of the image.

The key method is the drawImage() method:

context.drawImage(imageObj,destX,destY); 

imageObj is the image object, and destX and destY is where to position the image.

View in separate window

<!DOCTYPE HTML> 
<html>
    <head>
        <script>
            window.onload = function(){
                var canvas = document.getElementById("myCanvas");
                var context = canvas.getContext("2d");
                /*from w  w w.j  a  va  2  s. c o m*/
                var imageObj = new Image();
                imageObj.onload = function(){
                    var destX = canvas.width / 2 - this.width / 2;
                    var destY = canvas.height / 2 - this.height / 2;
                    
                    context.drawImage(this, destX, destY);
                };
                imageObj.src = "image2.png";
            };
        </script>
    </head>
    <body>
        <canvas id="myCanvas" width="600" height="250" style="border:1px solid black;">
        </canvas>
    </body>
</html>



PreviousNext

Related