HTML 캔버스 drawImage() 메서드

❮ HTML 캔버스 참조

사용할 이미지:

비명

예시

캔버스에 이미지를 그립니다.

귀하의 브라우저는 HTML5 캔버스 태그를 지원하지 않습니다.

자바스크립트:

window.onload = function() {
  var c = document.getElementById("myCanvas");
  var ctx = c.getContext("2d");
  var img = document.getElementById("scream");
  ctx.drawImage(img, 10, 10);
};

브라우저 지원

표의 숫자는 이 방법을 완전히 지원하는 첫 번째 브라우저 버전을 지정합니다.

Method
drawImage() Yes 9.0 Yes Yes Yes

정의 및 사용

drawImage() 메서드는 이미지, 캔버스 또는 비디오를 캔버스에 그립니다.

drawImage() 메서드는 이미지의 일부를 그리거나 이미지 크기를 늘리거나 줄일 수도 있습니다.

참고: 이미지가 로드되기 전에는 drawImage() 메서드를 호출할 수 없습니다. 이미지가 로드되었는지 확인하려면 window.onload() 또는 document.getElementById(" imageID ").onload에서 drawImage()를 호출할 수 있습니다.

자바스크립트 구문

캔버스에 이미지 위치 지정:

JavaScript syntax: context.drawImage(img,x,y);

캔버스에 이미지를 배치하고 이미지의 너비와 높이를 지정합니다.

JavaScript syntax: context.drawImage(img,x,y,width,height);

이미지를 자르고 잘린 부분을 캔버스에 배치합니다.

JavaScript syntax: context.drawImage(img,sx,sy,swidth,sheight,x,y,width,height);

매개변수 값

Parameter Description Play it
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)

더 많은 예

예시

캔버스에 이미지를 배치하고 이미지의 너비와 높이를 지정합니다.

귀하의 브라우저는 HTML5 캔버스 태그를 지원하지 않습니다.

자바스크립트:

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);
};

예시

이미지를 자르고 잘린 부분을 캔버스에 배치합니다.

귀하의 브라우저는 HTML5 캔버스 태그를 지원하지 않습니다.

자바스크립트:

window.onload = function() {
  var c = document.getElementById("myCanvas");
  var ctx = c.getContext("2d");
  var img = document.getElementById("scream");
  ctx.drawImage(img, 90, 130, 50, 60, 10, 10, 50, 60);
};

예시

사용할 비디오(시연을 시작하려면 재생을 누르십시오):

캔버스:

귀하의 브라우저는 HTML5 캔버스 태그를 지원하지 않습니다.

JavaScript(코드는 20밀리초마다 비디오의 현재 프레임을 그립니다):

var v = document.getElementById("video1");
var c = document.getElementById("myCanvas");
var ctx = c.getContext('2d');
var i;

v.addEventListener('play',function() {i=window.setInterval(function() {ctx.drawImage(v,5,5,260,125)},20);},false);
v.addEventListener('pause',function() {window.clearInterval(i);},false);
v.addEventListener('ended',function() {clearInterval(i);},false);

❮ HTML 캔버스 참조