Image

To draw any image, video or other canvas onto the canvas

  • turned_in_notImage Methods
    • drawImage()


drawImage( )

Used to draw image(s) on canvas

Syntax - To draw image with actual size

drawImage(image,x,y)

Syntax - To draw image with specific size

drawImage(image,x,y,width,height);

Syntax - To draw cliped portion of image with specific size

drawImage(image,clipX,clipY,clipWidth,clipHeight,x,y,width,height);

image - Any image/video/canvas element
clipX, clipY - Starting coordinate points on the actual image size along XY-axis to clip
clipWidth, clipHeight - Clipped width & height on the actual image from clipX & clipY points
x, y - Coordinate points at which you have to place your image
width, height - Specific size of your image or clipped-image to place on canvas

  • Note! To ensure that the image has been loaded, you must call drawImage() method inside 'load' event
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
window.onload = function() {
  var img=document.getElementById("img1");
  ctx.drawImage(img,10,20,80,80);     //with specific size
  ctx.drawImage(img,60,40,50,50,140,20,25,25);  //clipped
};
drawImagesubject
drawImageclose
<!DOCTYPE html>
<html>
<head>
<title>Full Code</title>
</head>
<body>
  <img src="/images/html5.png" id="img1" style="height:100px">
  <canvas id="canvas" width="200" height="100" style="border:1px solid teal;"></canvas>
<script>
  var canvas = document.getElementById("canvas");
  var ctx = canvas.getContext("2d");

/* Now we code to draw on canvas */
window.onload = function() {
  var img=document.getElementById("img1");
  ctx.drawImage(img,10,20,80,80);   // with specific size
  ctx.drawImage(img,60,40,50,50,140,20,25,25);  //clipped
};
</script>
</body>
</html>


var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var video=document.getElementById("video");
var interval;
video.addEventListener('play',function() {
    interval=setInterval(function() {ctx.drawImage(video,0,0,270,150)},20);
});
video.addEventListener('pause',function() {clearInterval(interval);});
video.addEventListener('ended',function() {clearInterval(interval);});
drawImage (Video)subject
drawImage (Video)close
<!DOCTYPE html>
<html>
<head>
<title>Full Code</title>
</head>
<body>
  <video id="video" controls width="270" src="/video/v.mp4"></video>
  <canvas id="canvas" width="270" height="150" style="border:1px solid teal;"></canvas>
<script>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var video=document.getElementById("video");
var interval;
video.addEventListener('play',function() {
    interval=setInterval(function() {ctx.drawImage(video,0,0,270,150)},20);
});
video.addEventListener('pause',function() {clearInterval(interval);});
video.addEventListener('ended',function() {clearInterval(interval);});
</script>
</body>
</html>


  • Path
TryOut Examples"Learn to Explore..!"

TryOut Editor

receipt