There are three steps to draw the canvas images
They are as follow,
context.drawImage(image, dx, dy);
context.drawImage(image, dx, dy, dw, dh);
context.drawimage(image, sx, sy, sw, sh, dx, dy, dw, dh);
Canvas images uses the syntax as drawimage()
method to draw the image or to increase the size of the image
<canvas id="myCanvas" width="500" height="200"></canvas> <script> var canvas = document.getElementById('myCanvas'); var context = canvas.getContext('2d'); var imageObj = new Image(); imageObj.onload = function () { context.drawImage(imageObj, 20, 40); }; imageObj.src = "http://techfunda.com/HTPictures/Generics/1-635716259621984414.jpg"; </script>
In the above code snippet we have defined the images in canvas, We have canvas id as "mycanvas"
and width as "500"
and height as "200
"
context.drawImage(imageObj, 20, 40);
- It defines the image with x, y positionsIn the last step we have defined the url of the image
output
Image size
It defines the size of the image with the width and height
<canvas id="myCanvas" width="278" height="400"></canvas> <script> var canvas = document.getElementById('myCanvas'); var context = canvas.getContext('2d'); var x = 20; var y = 15; var width = "200"; var height = "350"; var imageObj = new Image(); imageObj.onload = function () { context.drawImage(imageObj, x, y, width, height); }; imageObj.src = "http://techfunda.com/HTPictures/Generics/1-635716259621984414.jpg"; </script>
In the above code snippet we have defined the images in canvas, We have canvas id as "mycanvas"
and width as "278
" and height as "400"
"myCanvas"
context.drawImage(imageObj, x, y, width, height);
- It defines the image with x, y positionsIn the last step we have defined the with the url of the image
output
It is used to rotate the image
<canvas id="canvas" width=300 height=300></canvas> <script> var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var img = new Image(); img.onload = start; img.src = "http://techfunda.com/HTPictures/Generics/5-635898849972807270.JPG"; function start() { ctx.translate(150, 150); ctx.rotate(Math.PI / 2); ctx.drawImage(img, -img.width / 2, -img.height / 2); ctx.rotate(-Math.PI / 2); ctx.translate(-canvas.width / 2, -canvas.height / 2); ctx.fillRect(0, 0, 25, 10); } </script>
output
Views: 5937 | Post Order: 38