Javascript examples for Canvas Reference:drawImage
The drawImage() method draws an image, canvas, or video onto the canvas.
To draw the image on the canvas:
context.drawImage(img, x, y);
To draw the image on the canvas, and set width and height of the image:
context.drawImage(img, x, y, width, height);
To Clip the image:
context.drawImage(img, sx, sy, swidth, sheight, x, y, width, height);
Parameter | Description |
---|---|
img | the image/canvas/video element to use |
x | The x coordinate where to place the image on the canvas |
y | The y coordinate where to place the image on the canvas |
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 |
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) |
The following code shows how to draw the image on the canvas, and set width and height of the image.
JavaScript:
<!DOCTYPE html> <html> <body> <p>Image to use:</p> <img id="scream" width="220" height="277" src="http://java2s.com/resources/c.png" alt="The Scream"> <p>Canvas:</p> <canvas id="myCanvas" width="240" height="300" style="border:1px solid #d3d3d3;"> Your browser does not support the HTML5 canvas tag. </canvas>/*ww w .java2s. co m*/ <script> window.onload = function() { var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); var img = document.getElementById("scream"); ctx.drawImage(img, 10, 10, 150, 180); } </script> </body> </html>