Draw an Image on Html5 Canvas?

HTML5 Canvas / JavaScript Graphics

May 24, 2017

DRAW AN IMAGE ON HTML5 CANVAS

Use HTML5 canvas’ drawImage method in JavaScript.

Discussion

To draw an image using HTML5 Canvas, we can use the drawImage() method which requires an image object and a destination point. The destination point defines the top left corner of the image relative to the top left corner of the canvas.

Since the drawImage() method requires an image object, we must first create an image and wait for it to load before instantiating drawImage(). We can accomplish this by using the onload property of the image object.

Definition

The drawImage() method draws an image, canvas, or video onto the canvas.
The drawImage() method can also draw parts of an image, and/or increase/reduce the image size.

Syntax

Position the image on the canvas:

context.drawImage(img,x,y);

Position the image on the canvas, and specify width and height of the image:

context.drawImage(img,x,y,width,height);

Clip the image and position the clipped part on the canvas:

context.drawImage(img,sx,sy,swidth,sheight,x,y,width,height);

Parameter

img  >	Specifies the image, canvas, or video element to use.
sx   >	Optional. The x coordinate where to start clipping.
sy   >	Optional. The y coordinate where to start clipping.
swidth >  Optional. The width of the clipped image.
sheight >  Optional. The height of the clipped image.
x    >	The x coordinate where to place the image on the canvas.
y    >	The y coordinate where to place the image on the canvas.
width  >   Optional. The width of the image to use (stretch or reduce the image).
height  >  Optional. The height of the image to use (stretch or reduce the image).

Example

<!DOCTYPE HTML>
<html>
  <head>
    <style>
      body {
        margin: 0px;
        padding: 0px;
      }
    </style>
  </head>
  <body>
    <canvas id="myCanvas" width="578" height="400"></canvas>
    <script>
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');
      var imageObj = new Image();

      imageObj.onload = function() {
        context.drawImage(imageObj, 69, 50);
      };
      imageObj.src = 'https://webtaxonomy.com/wp-content/uploads/2017/05/log-icon-wt.png';
    </script>
  </body>
</html>

Leave a Reply

Your email address will not be published. Required fields are marked *

Recent Posts

Tags

Related Posts

Many new updates happened for Android developers lately after Google I/O. Initially there was no restriction on some features but now.
phpMyAdmin is a web-based database management tool that you can use to view and edit the MySQL databases on your EC2 instance.
Title attribute can be helpful to expand on the meaning of your navigation label and give your users more context You can provide to the link.