How do you draw an image on HTML5 canvas?
Use HTML5 canvas' drawImage method in JavaScript:
The drawImage method can be invoked with three different set of arguments:
- context.drawImage(image, dx, dy)
- context.drawImage(image, dx, dy, dw, dh)
- context.drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh)
where d represents the destination canvas and s represents the source image.
drawImage(image, dx, dy)
var context = document.getElementById('canvas1').getContext("2d"); var img = new Image(); img.onload = function () { context.drawImage(img, 0, 0); } img.src = "images/watermelon-duck.png";
drawImage(image, dx, dy, dw, dh)
var context = document.getElementById('canvas2').getContext("2d"); var img = new Image(); img.onload = function () { context.drawImage(img, 75, 55, 150, 110); } img.src = "images/watermelon-duck.png";
drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh)
var context = document.getElementById('canvas3').getContext("2d"); var img = new Image(); img.onload = function () { context.drawImage(img, 100, 100, 150, 110, 0, 0, 300, 220); } img.src = "images/watermelon-duck.png";