html tutorial - drawImage Method in HTML5 Canvas - html5 - html code - html form



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

Syntax for drawImage() Method in HTML5 Canvas:

context.drawImage(img,x,y); 

Property values for drawImage() Method in HTML5 Canvas:

Values Description
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)

Sample coding for drawImage Method in HTML5 Canvas:

Tryit<!DOCTYPE html>
<html>
    <head>
        <title>Wikitechy drawImage Method</title>
    </head>
    <body>
        <h2>Wikitechy drawImage Method</h2>
        <p>Image to use:</p>
        <img id="scream" width="200" height="200" src="logo.png" alt="The Scream">
        <canvas id="wikitechyCanvas" width="200" height="200" 
                style="border:1px solid blue;"> </canvas>
        <script>
            window.onload = function()
            {
                var c = document.getElementById("WikitechyCanvas");
                var context = c.getContext("2d");
                var img = document.getElementById("scream");
                context.drawImage(img, 10, 10);
            }
        </script>
    </body>
</html>

Code Explanation for drawImage Method in HTML5 Canvas:

drawImage method in HTML5 canvas Code Explanation

  1. “Scream” is used to define the value id attribute for normal image element.
  2. “wikitechyCanvas” is used to define the value id attribute for canvas element.
  3. Window.onload function is used to load the image.
  4. The getElementById(); method is used to get the element that has the id attributes with the identified value (“wikitechycanvas”).
  5. The getElementById(); method is used to get the element that has the id attributes with the identified value (“scream”).
  6. drawImage() method is used to draw the image in the canvas.drawImgae(img,10,10).

Output for drawImage Method in HTML5 Canvas:

drawImage method in HTML5 canvas Output

  1. The without canvas Wikitechy.com image is normal image.
  2. The canvas Rectangle with blue border.
  3. The within canvas Wikitechy.com image is output image.

Browser Support for drawImage Method in HTML5 Canvas:

Yes 9.0 Yes Yes Yes

Related Searches to accept Attribute in html