Как бы я использовал загруженное пользователем изображение в качестве фонового изображения для скользящей головоломки, над которой я работаю? - PullRequest
0 голосов
/ 25 апреля 2020

Я пытаюсь сделать так, чтобы при загрузке пользователем файла изображения он автоматически использовался в качестве фонового изображения в головоломке. Я пытался посмотреть, как я это сделаю, и я чувствую, что это будет так сложно, но у меня просто пукнет мозг. Я также надеюсь запустить таймер, как только изображение будет загружено, но я чувствую, что это то, что я, вероятно, смогу выяснить сам, но любые советы, безусловно, будут оценены.

html:

<!DOCTYPE html>
<html>
    <head>
        <script src="functions.js"></script>
        <link rel="stylesheet" href="design.css" type="text/css">
        <meta charset="UTF-8">
        <title>Puzzle</title>

    </head> 

    <body>

        <div class="file-upload">
        <input class="file-upload__input" type="file" name="picture" id="picture" accept="image/*">
        <button class="file-upload__button" type="button">Choose a Photo</button>
        <span class="file-upload__label"></span>
     </div>

<!--button formating-->
        <script>
            Array.prototype.forEach.call(document.querySelectorAll(".file-upload__button"), function(button) {
                const hiddenInput = button.parentElement.querySelector(".file-upload__input");
                const label = button.parentElement.querySelector(".file-upload__label");
                const defaultLabelText = "No file(s) selected";

                // Set default text for label
                label.textContent = defaultLabelText;
                label.title = defaultLabelText;

                button.addEventListener('click', function(){
                    hiddenInput.click();
                });
                hiddenInput.addEventListener('change', function(){
                    const filenameList = Array.prototype.map.call(hiddenInput.files, function (file){
                        return file.name;
                    });
                    label.textContent = filenameList.join(', ') || defaultLabelText;
                    label.title = label.textContent;
                });
            });
        </script>
<!--Puzzle-->
<center><div id="table" style="display: table;">
    <div id="row1" style="display: table-row;">
       <div id="cell11" class="tile1" onClick="clickTile(1,1);"></div>
       <div id="cell12" class="tile2" onClick="clickTile(1,2);"></div>
       <div id="cell13" class="tile3" onClick="clickTile(1,3);"></div>
    </div>
    <div id="row2" style="display: table-row;">
       <div id="cell21" class="tile4" onClick="clickTile(2,1);"></div>
       <div id="cell22" class="tile5" onClick="clickTile(2,2);"></div>
       <div id="cell23" class="tile6" onClick="clickTile(2,3);"></div>
    </div>
    <div id="row3" style="display: table-row;">
       <div id="cell31" class="tile7" onClick="clickTile(3,1);"></div>
       <div id="cell32" class="tile8" onClick="clickTile(3,2);"></div>
       <div id="cell33" class="tile9" onClick="clickTile(3,3);"></div>
    </div>
 </div>
   <button onClick="shuffle();">New Game</button>
 </center>
</body>
 </html>

CSS:

body { 
    background: #002a3f;
    }
.file-upload {
    display: inline-flex;
    align-items: center;
    font-size: 20px;

}
.file-upload__input {
    display: none;
}

.file-upload__button {
    -webkit-appearance: none;
    background: #009879;
    border: 2px solid #00745d;
    border-radius: 4px;
    outline: none;
    padding: 0.5em 0.8em;
    margin-right: 15px;
    color: white;
    font-size: 1em;
    font-family: sans-serif;
    font-weight: bold;
    cursor: pointer;
}

.file-upload__button:active{
    background: #00745d;
}

.file-upload__label{
    max-width: 250px;
    font-size: 0.95em;
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
}

    .tile1, .tile2, .tile3, .tile4, .tile5, .tile6, .tile7, .tile8, .tile9 {
      display: table-cell;
      width: 120px;
      height: 120px;
      border: 1px solid rgb(100, 100, 100);
      background: url(); 
      cursor: pointer;
    }

    .tile1 {background-position: left top;}
    .tile2 {background-position: center top;}
    .tile3 {background-position: right top;}
    .tile4 {background-position: left center;}
    .tile5 {background-position: center center;}
    .tile6 {background-position: right center;}
    .tile7 {background-position: left bottom;}
    .tile8 {background-position: center bottom;}
    .tile9 {background: rgb(58, 58, 58); cursor: default;}

JS:

function swapTiles(cell1,cell2) {
    var temp = document.getElementById(cell1).className;
    document.getElementById(cell1).className = document.getElementById(cell2).className;
    document.getElementById(cell2).className = temp;
  }

  function shuffle() {
  //Use nested loops to access each cell of the 3x3 grid
  for (var row=1;row<=3;row++) { //For each row of the 3x3 grid
     for (var column=1;column<=3;column++) { //For each column in this row

      var row2=Math.floor(Math.random()*3 + 1); //Pick a random row from 1 to 3
      var column2=Math.floor(Math.random()*3 + 1); //Pick a random column from 1 to 3

      swapTiles("cell"+row+column,"cell"+row2+column2); //Swap the look & feel of both cells
    } 
  } 
  }

  function clickTile(row,column) {
    var cell = document.getElementById("cell"+row+column);
    var tile = cell.className;
    if (tile!="tile9") { 
         //Checking if white tile on the right
         if (column<3) {
           if ( document.getElementById("cell"+row+(column+1)).className=="tile9") {
             swapTiles("cell"+row+column,"cell"+row+(column+1));
             return;
           }
         }
         //Checking if white tile on the left
         if (column>1) {
           if ( document.getElementById("cell"+row+(column-1)).className=="tile9") {
             swapTiles("cell"+row+column,"cell"+row+(column-1));
             return;
           }
         }
           //Checking if white tile is above
         if (row>1) {
           if ( document.getElementById("cell"+(row-1)+column).className=="tile9") {
             swapTiles("cell"+row+column,"cell"+(row-1)+column);
             return;
           }
         }
         //Checking if white tile is below
         if (row<3) {
           if ( document.getElementById("cell"+(row+1)+column).className=="tile9") {
             swapTiles("cell"+row+column,"cell"+(row+1)+column);
             return;
           }
         } 
    }

  }

1 Ответ

1 голос
/ 25 апреля 2020

Вы можете использовать изображение клиента, даже не загружая его. Способ сделать это - использовать FileReader API. Ознакомьтесь с учебником Mozilla по FileReader.readAsDataURL () .

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...