HTML5 Game - Canvas Image

Introduction

The following code draws a simple image.

Demo

ResultView the demo in separate window

<!DOCTYPE HTML> 
<html>
    <head>
        <script>
            window.onload = function(){
                let canvas = document.getElementById("myCanvas");
                let context = canvas.getContext("2d");
                //  w w  w  .ja v a2  s.  com
                let imageObj = new Image();
                imageObj.onload = function(){
                    let destX = canvas.width / 2 - this.width / 2;
                    let destY = canvas.height / 2 - this.height / 2;
                    
                    context.drawImage(this, destX, destY);
                };
                imageObj.src = "http://java2s.com/style/download.png";
            };
        </script>
    </head>
    <body>
        <canvas id="myCanvas" width="600" height="250" style="border:1px solid black;">
        </canvas>
    </body>
</html>

Note

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

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

The method drawImage() is as follows:

context.drawImage(imageObj,destX,destY); 

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

We can also add two additional parameters, destWidth and destHeight to define the resize of our image during drawing:

context.drawImage(imageObj,destX,destY,destWidth,destHeight); 

Related Topics