Introduction

Welcome back to my "HTML5 Canvas For Beginners" article series Part-IV. If you are new to HTML5 Canvas then I suggest you read my previous articles:
- HTML5 Canvas For Beginners - Part-1: Basic Drawings
- HTML5 Canvas For Beginners - Part-2: Curves & Shapes
- HTML5 Canvas For Beginners - Part-3: Gradients
In today's article we learn all about HTML5 Canvas Images.
HTML5 Canvas Images
In HTML5 Canvas, we can draw an image using the "drawImage()" method in which we need an image object and a destination point. As we know, the drawImage() method needs an image object, so we need to create an image and wait until it loads on the canvas. We can do this using the "onload" property of the image object.
Example:
- <body>
- <form id="form1" runat="server">
- <div>
- <canvas id="drawCanvas" width="600" height="500"></canvas>
- <script>
- var drawCanvas = document.getElementById('drawCanvas');
- var ctx = drawCanvas.getContext('2d');
- //Declare an image object
- var imgObj = new Image();
- imgObj.onload = function () {
- ctx.drawImage(imgObj, 5, 80);
- };
- //Image source
- imgObj.src = 'images/disney1.jpg';
- </script>
- </div>
- </form>
- </body>
Output

Image Size
In HTML5 Canvas, we can set the size of an image by adding two more parameters in the "drawImage()" method, "width" and "height".
Example:
- <body>
- <form id="form1" runat="server">
- <div>
- <canvas id="drawCanvas" width="600" height="500"></canvas>
- <script>
- var drawCanvas = document.getElementById('drawCanvas');
- var ctx = drawCanvas.getContext('2d');
- var x = 100;
- var y = 120;
- var w = 400;
- var h = 300;
- var imgObj1 = new Image();
- imgObj1.onload = function ()
- {
- ctx.drawImage(imgObj1, x, y, w, h);
- }
- imgObj1.src = 'images/Captain.jpg';
- var imgObj2 = new Image();
- imgObj2.onload = function () {
- ctx.drawImage(imgObj2, 0, 0, 600, 100);
- }
- imgObj2.src = 'images/image.jpg';
- </script>
- </div>
- </form>
- </body>




Gyanender SharmaPosted Aug 16, 2013, 1:39 PM
Thanks Kailash
Former memberPosted Aug 16, 2013, 7:21 AM
Very Nice, i appreciated