본문 바로가기

뚱땅뚱땅

[HTML5/JavaScript] 직소퍼즐 만들기 - 2: 드래그드롭으로 퍼즐넣기

dog-foooot.tistory.com/20

 

[HTML5/JavaScript] 직소퍼즐 만들기 - 1 : 파일 입력

안녕하세요, 김선진입니다. 주말에 블로그 글을 3개나 써야 해서(업보...) 시리즈물로 쓰려고 직소퍼즐 만들기를 기획했는데요, 코딩하는 동안 스크린샷찍는 걸 까먹어서... 1탄에서는 input과 canva

dog-foooot.tistory.com

const numColsToCut = 4;
const numRowsToCut = 4;
function allowDrop(ev) {
  ev.preventDefault();
}

function drag(ev) {
  ev.dataTransfer.setData("text", ev.target.id);
}

function drop(ev) {
  ev.preventDefault();
  var data = ev.dataTransfer.getData("text");
  if (!data) return;
  if (ev.target.nodeName !== 'TD') {
    console.log(ev.target.parentNode);
    const currentImage = ev.target;
    const td = ev.target.parentNode;
    td.removeChild(currentImage);
    td.appendChild(document.getElementById(data))
    const box = document.getElementById('puzzle-box');
    box.appendChild(currentImage);
    return;
  }
  ev.target.appendChild(document.getElementById(data));
}

function updateImageDisplay() {
  const preview = document.querySelector('.preview');
  const input = document.querySelector('input');
  while(preview.firstChild) {
    preview.removeChild(preview.firstChild);
  }
  const curFiles = input.files;
    for(const file of curFiles) {
         const para = document.createElement('p');
         const imageItem = document.createElement('div');
           const img = new Image();
           img.onload = function() {
             const widthOfOnePiece = this.width/numColsToCut;
             const heightOfOnePiece = this.height/numRowsToCut;
             para.innerHTML = `${numColsToCut}X${numRowsToCut}로 생성된 퍼즐입니다.`;

              const imagePieces = [];
              const board = document.getElementById('puzzle-board');
              const box = document.getElementById('puzzle-box');
              while(board.firstChild) {
                board.removeChild(board.firstChild);
              }
                 for(var x = 0; x < numColsToCut; ++x) {
                    let tableRow = document.createElement('tr');
                     for(var y = 0; y < numRowsToCut; ++y) {
                         var canvas = document.createElement('canvas');
                         canvas.width = widthOfOnePiece;
                         canvas.height = heightOfOnePiece;
                         var context = canvas.getContext('2d');
                         context.drawImage(img, y * widthOfOnePiece, x * heightOfOnePiece, widthOfOnePiece, heightOfOnePiece, 0, 0, canvas.width, canvas.height);
                         let pieceImage = new Image();
                         pieceImage.src = canvas.toDataURL();
                         pieceImage.id = canvas.toDataURL();
                         pieceImage.draggable = true;
                         pieceImage.ondragstart = drag;
                         let tableData = document.createElement('td');
                         tableData.ondrop = drop;
                         tableData.ondragover = allowDrop;
                         tableData.width = widthOfOnePiece;
                         tableData.height = heightOfOnePiece;
                         box.appendChild(pieceImage);
                         tableRow.appendChild(tableData);
                         imagePieces.push(canvas.toDataURL());
                     }
                     board.appendChild(tableRow);
                 }
           }
           img.src = URL.createObjectURL(file);

           imageItem.appendChild(img);
           imageItem.appendChild(para);
           preview.appendChild(imageItem);
     }
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script src="puzzle.js"></script>
    <title>PUZZLE GAME</title>
</head>
<body>
    <div class="puzzle-container">
        <div>
            퍼즐게임
        </div>
        <label for="puzzle-input">
            이미지 선택
            <input onchange="updateImageDisplay()" name="puzzle-input" id="puzzle-input" type="file" accept="image/*">
        </label>
        <div class="preview">
            <p>선택한 이미지로 퍼즐을 만듭니다.</p>
        </div>
        <table id="puzzle-board">

        </table>
        <div id="puzzle-box">

        </div>
    </div>
</body>
</html>

<style>
    input {
    opacity: 0;
    }
    table {
    border: 1px solid black;
    border-spacing: 0;
    box-sizing: border-box;
    }
    td {
    border: 1px solid black;
    padding:0px !important;
    box-sizing: border-box;
    border-spacing: unset;
    border-collapse: collapse;
    }
    td img {
    display: block;
    }
    img:hover {
    box-sizing:border-box;
    outline: solid 2px red;
    }
</style>