Develop/canvas

22. Slicing - 이미지 자르기(크롭)

GuriZzang 2015. 8. 10. 15:30

GuriZzang.com에 오시면 

더 자세한 내용을 보실 수 있습니다.


.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)

이미지를 자릅니다.

  • .drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)
  • 인자 : img
  • 설명 : 이미지객체
  • 인자 : sx
  • 설명 : 이미지를 자를 영역의 시작 x좌표
  • 인자 : sy
  • 설명 : 이미지를 자를 영역의 시작 y좌표
  • 인자 : sWidth
  • 설명 : 이미지를 자를 영역 넓이
  • 인자 : sHeight
  • 설명 : 이미지를 자를 영역 높이
  • 인자 : dx
  • 설명 : 자른 이미지가 그려지는 x좌표
  • 인자 : dy
  • 설명 : 자른 이미지가 그려지는 y좌표
  • 인자 : dWidth
  • 설명 : 자른 이미지의 넓이
  • 인자 : dHeight
  • 설명 : 자른 이미지의 높이



전 게시글에서 기본적인 drawImage로 이미지에 대해 살짝 봤는데요.

.drawImage( img,x,y )  //이미지와 시작좌표

.drawImage( img,x,y,width, height )  //이미지 시작좌표, 확대축소

.drawImage() 전 게시글 보기



.drawImage()는 인자에 따라서 생성된 이미지만 그리느냐, 이미지를 확대/축소, 이미지를 크롭 후 확대/축소가 전부 가능합니다. 이번에는 Slicing을 볼건데요. 위의 설명처럼 인자가 많네요.. 당췌 뭔 말인지 모를수도 있겠지만.. 최대한 알기쉽게 설명해 보겠습니다.



drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)

인자의 순서대로 설명을 하자면


1. image : 이미지/캔버스의 요소등을 생성한 (이미지)객체.

2. sx : (그려지는 좌표아님!) 크롭할 영역의 시작 x좌표.

3. sy (그려지는 좌표아님!) 크롭할 영역의 시작 y좌표.

4. sWidth (그려지는 좌표아님!) 크롭할 영역의 넓이.

5. sHeight (그려지는 좌표아님!) 크롭할 영역의 높이.

6. dx : 크롭된 이미지가 그려질 영역의 x좌표.

7. dy 크롭된 이미지가 그려질 영역의 y좌표.

8. dWidth 크롭된 이미지의 넓이(확대/축소가 가능합니다). 위의 sWidth와 같으면 1:1 비율.

9. dHeight : 크롭된 이미지의 높이(확대/축소가 가능합니다). 위의 sHidth와 같으면 1:1 비율.


기본적인 drawImage( img, x, y, width, height )의 경우

1.이미지

2.이미지 시작x좌표

3.이미지 시작y좌표

4.이미지넓이

5.이미지높이

인데반해 slicing의 경우 인자의 순서가 달라집니다. 제일 헷갈리는 경우기 때문에 인자의 순서를 유의하시기 바랍니다.


밑의 이미지를 같이 한번 보세요.




먼저 두개의 소스가 있습니다.



Source1 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <script type="text/javascript" src="/_include/Lib/jquery/jquery-2.1.4.min.js"></script>
    <style>
        html, body {height:100%; width:100%; padding:0px; margin:0px;}
    </style>
    <script>
        function draw() {
            var canvas = document.getElementById('canvas');
            var ctx = canvas.getContext('2d');
             
            var img = new Image();
            img.src = 'https://mdn.mozillademos.org/files/5397/rhino.jpg';
            img.onload = function(){
                ctx.drawImage( img, 33, 71, 104, 124, 21, 20, 87, 104 );
            }
            var frame = new Image();
            frame.onload = function(){
                ctx.drawImage( frame, 0, 0 );
            }
             
        }
    </script>
</head>
<body onload="draw();">
 
<canvas id="canvas" width="300" height="300"></canvas>
 
</body>
</html>


Source2 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <script type="text/javascript" src="/_include/Lib/jquery/jquery-2.1.4.min.js"></script>
    <style>
        html, body {height:100%; width:100%; padding:0px; margin:0px;}
    </style>
    <script>
        function draw() {
            var canvas = document.getElementById('canvas');
            var ctx = canvas.getContext('2d');
             
            // Draw slice
            ctx.drawImage(document.getElementById('source'),
            33, 71, 104, 124, 21, 20, 87, 104);
             
            // Draw frame
            ctx.drawImage(document.getElementById('frame'),0,0);
        }
    </script>
</head>
<body onload="draw();">
 
<canvas id="canvas" width="150" height="150"></canvas>
<div style="display:none;">
    <img id="source" src="https://mdn.mozillademos.org/files/5397/rhino.jpg" width="300" height="227">
    <img id="frame" src="https://mdn.mozillademos.org/files/242/Canvas_picture_frame.png" width="132" height="150">
</div>
 
</body>
</html>


소스1과 소스2는 동일한 결과를 보여줍니다.

소스1의 경우 모든 이미지를 스크립트 코드에서 동적으로 로드해서 그리는 반면 소스2의 경우 html영역에 코딩된 이미지태그를 소스로 사용하고 있습니다. 이미지를 추가할 경우 스크립트 코드에서 추가를 해줘야 하겠죠.

코딩 방법에 따라 다르긴 하겠지만 게임등의 경우 body에 이미지태그등이 없이 동적으로 로드를 해야할 경우 소스1과 같은 방법으로 사용을 하시면 될듯하고 코더가 스크립트 코드를 건들지 않고 body에 이미지 태그를 추가하면 이미지를 사용할 수 있게 만들 수 있을겁니다.


아래는 위의 소스의 데모입니다.


Demo




아래의 예제는 소스2를 조금 응용한 예제입니다.

body에 img태그를 이용해서 이미지를 로드시킨 후 스크립트 코드에서 각 이미지의 갯수만큼 for문을 돌려 소스로 사용합니다.


Source 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <script type="text/javascript" src="/_include/Lib/jquery/jquery-2.1.4.min.js"></script>
    <style>
        html, body {height:100%; width:100%; padding:0px; margin:0px;}
        body {
            background: 0 -100px repeat-x url(https://mdn.mozillademos.org/files/5415/bg_gallery.png) #4F191A;
            margin: 10px;
        }
        img {
            display: none;
        }
        table {
            margin: 0 auto;
        }
        td {
            padding: 15px;
        }
    </style>
    <script>
        function draw() {
            // Loop through all images
            for (var i=0;i<document.images.length;i++){
                // Don't add a canvas for the frame image
                if (document.images[i].getAttribute('id')!='frame'){
                    // Create canvas element
                    canvas = document.createElement('canvas');
                    canvas.setAttribute('width',132);
                    canvas.setAttribute('height',150);
                    // Insert before the image
                    document.images[i].parentNode.insertBefore(canvas,document.images[i]);
                    ctx = canvas.getContext('2d');
                    // Draw image to canvas
                    ctx.drawImage(document.images[i],15,20);
                    // Add frame
                    ctx.drawImage(document.getElementById('frame'),0,0);
                }
            }
        }
    </script>
</head>
<body onload="draw();">
 
    <table>
        <tr>
            <td><img src="https://mdn.mozillademos.org/files/5399/gallery_1.jpg"></td>
            <td><img src="https://mdn.mozillademos.org/files/5401/gallery_2.jpg"></td>
            <td><img src="https://mdn.mozillademos.org/files/5403/gallery_3.jpg"></td>
            <td><img src="https://mdn.mozillademos.org/files/5405/gallery_4.jpg"></td>
        </tr>
        <tr>
            <td><img src="https://mdn.mozillademos.org/files/5407/gallery_5.jpg"></td>
            <td><img src="https://mdn.mozillademos.org/files/5409/gallery_6.jpg"></td>
            <td><img src="https://mdn.mozillademos.org/files/5411/gallery_7.jpg"></td>
            <td><img src="https://mdn.mozillademos.org/files/5413/gallery_8.jpg"></td>
        </tr>
    </table>
    <img id="frame" src="https://mdn.mozillademos.org/files/242/Canvas_picture_frame.png" width="132" height="150">
 
</body>
</html>



갤러리 DEMO 새창으로 보기

Demo

'Develop > canvas' 카테고리의 다른 글

24. restore() - 저장된 스타일 복원  (0) 2015.08.10
23. save() - 현재 스타일저장  (0) 2015.08.10
21. drawImage() - 이미지 사용하기  (0) 2015.08.10
20. nonzero - 필터규칙  (0) 2015.08.10
19. shadow - 그림자  (0) 2015.08.10