자바스크립트 HTML 캔버스 drawImage() 메소드

행복햐 2017. 8. 18. 13:25

구조

context.drawImage ( img, sourceX, sourceY, sourceWidth, sourceHight, x, y, Width, Hight )


설명

img : 사용할 이미지

sourceX : 이미지 안에서 x 좌표

sourceY : 이미지 안에서 y 좌표

sourceWidth : 사용할 폭

sourceHight : 사용할 높이

x : 캔버스 안에서 x 좌표

y : 캔버스 안에서 y 좌표

Width : 사용할 폭

Hight : 사용할 높이


예제

<p>사용한 이미지</p>

<img id="alien" width="240" height="277" src="https://github.com/gregquat/inbeda/raw/master/sprite.png" style="background-color: black">


<p>캔버스:</p>

<canvas id="myCanvas" width="240" height="297" style="border:1px solid #d3d3d3;background-color:black">

Your browser does not support the HTML5 canvas tag.

</canvas>


<script>

window.onload = function() {

    var c = document.getElementById("myCanvas");

    var ctx = c.getContext("2d");

    var img = document.getElementById("alien");

    ctx.drawImage(img, 0,0,28,20,10, 10, 28, 20);

    ctx.drawImage(img, 0,0,28,20,40, 10, 28, 20);

    ctx.drawImage(img, 30,0,28,20,10, 28, 28, 20);


}

</script>

실행결과


사용한 이미지

The Scream

캔버스:

Your browser does not support the HTML5 canvas tag.

참고: https://www.w3schools.com/