Loading an image and show in HTML5 canvas

Lets start our next javascript example, To test that everything is fine you can use alert for debugging purpose, if alert display its fine otherwise some issue with code

<!DOCTYPE HTML>
<html>
    <head>
        <script>

            window.onload = function(){
                alert("Everything Working fine");
            };

        </script>
    </head>
    <body>
        <canvas id="myCanvas" width="600" height="400">
        </canvas>
    </body>
</html>

we can rewrite our javascript code in new js file and use it as below

window.onload = function(){
    alert("Everything Working fine");
};

and use in our html template as below

<!DOCTYPE HTML>
<html>
    <head>
        <script src="js/main.js">
        </script>
    </head>
    <body>
        <canvas id="myCanvas" width="600" height="400">
        </canvas>
    </body>
</html>

now replace alert function in our javascript with this code

// get canvas element reference
var canvas = document.getElementById("myCanvas");
// get context object
var context = canvas.getContext("2d");
// create image Object
var imageObj = new Image();
// create position variable
var destX = 50;
var destY = 100;
// onload handler
imageObj.onload = function(){
    context.drawImage(imageObj, destX, destY);
};
// loading request
imageObj.src = "img/avatar.png";

Now our image is attached to canvas isn’t simple

Advertisements

About Jeetendra Chauhan

I am a s/w developer. love to code
This entry was posted in HTML5 and tagged , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s