Share Blog

Tuesday, September 08, 2015

How to Draw Images on Canvas in HTML 5

Introduction:
Let’s have some knowledge of the canvas images by understanding its function for drawing the images. To draw a canvas image, the drawImage() method is used that requires an images object and a destination point. The destination point means the top-left corner of the images relative to the top-left corner of the canvas on which the image is to be drawn.
There are the following three variants of this method.
v  drawImage(image, dx, dy).
v  drawImage(image, dx, dy, dw, dh)
v  drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh,).


First we should know about all the parameters given in the methods, so we can understand the use of all the parameters and can easily play with the images.

The parameter "images" is the image that is to be drawn.

The parameters "dx" and "dy" are known as "destinationX" and "destinationY" respectively and determine where the image is to be drawn on the canvas.

The parameters "dw" and "dh" are known as "destinationWidth" and "destinationHeight" respectively and determine the scale size of the image.

The parameters "sx" and "sy" are known as "sourceX" and "sourceY" respectively and determine the where in the source images to start copying the rectangle of the images onto the canvas.

The parameters "sw" and "sh" are known as "sourceWidth" and "sourceHeight" respectively and determine the scaling (extent of copying of width and height) of the source image.

As we all know, the drawImage() method needs an object, so first we should create an image object and should wait for it to load by applying the 
 window.onload() function before the initiation ofthe drawImages() method.




<%@ Page Language="C#" AutoEventWireup="true" CodeFile="HTML5_CANVAS.aspx.cs" Inherits="HTML5_CANVAS" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div style="float: left;">
        <p>Image being used:</p>
        <img id="sunil" width="200" height="230" src="Images/sunil.jpg" alt="blank">
    </div>
    <div style="float: left;margin-left:60px;">
        <p>Canvas Image:</p>
        <canvas id="smokeCanvas" width="250" height="170" style="border: 2px solid blue;">
            <script>
                window.onload = function ashSkull() {
                    var newCanvas = document.getElementById("smokeCanvas");
                    var context = newCanvas.getContext("2d");
                    var image = document.getElementById("sunil");
                    context.drawImage(image, 0, 0);
                }
            </script>
        </canvas>
    </div>
    </form>
</body>
</html>


Output




No comments:

Post a Comment