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:
1 |
context.drawImage(img,x,y); |
Position the image on the canvas, and specify width and height of the image:
1 |
context.drawImage(img,x,y,width,height); |
Clip the image and position the clipped part on the canvas:
1 |
context.drawImage(img,sx,sy,swidth,sheight,x,y,width,height); |
Parameter
1 2 3 4 5 6 7 8 9 |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<!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> |