javascript結合Flexbox簡單實現滑動拼圖遊戲_javascript技巧

來源:互聯網
上載者:User

滑動拼圖就是把一張圖片分成幾等份,打亂順序(下圖),然後通過滑動拼湊成一張完整的圖片。

要實現一個拼圖遊戲,需要考慮怎樣隨機的打亂順序,怎樣交換兩張圖片的位置,等等。但是,使用了Flexbox布局以後,這都不需要你去考慮,瀏覽器會幫你做,Flexbox就是這麼的強大。關於Flexbox的介紹可以點擊這裡。
這個遊戲中要用的是Flexbox布局的order屬性,order屬性可以用來控制Flex項目的順序。
這裡我用九個canvas元素來把圖片分成九等分,也可以用其他方法,比如背景圖片定位:

<div class="wrap">  <canvas></canvas>  <canvas></canvas>  <canvas></canvas>  <canvas></canvas>  <canvas></canvas>  <canvas></canvas>  <canvas></canvas>  <canvas></canvas>  <canvas></canvas></div>

如果不僅限於九宮格,還要十六宮格等,上面的元素完全可以動態產生。
下面是產生打亂順序的九張圖代碼:

var drawImage = function (url) {  return new Promise(function (resolve, reject) {    var img = new Image();    img.onload = function () {      resolve(img);    };    img.src = url;  })};drawImage("2.jpg").then(function (img) {  var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];  var random = arr.sort(function() {return Math.random() > 0.5});  [].forEach.call(document.querySelectorAll("canvas"), function (item, i) {    item.width = $(".wrap").clientWidth / 3;    item.height = $(".wrap").clientHeight / 3;    item.style.order = random[i];    var ctx = item.getContext("2d");    ctx.drawImage(img, img.width * (i % 3) / 3, img.height * Math.floor(i / 3) / 3, img.width / 3, img.height / 3, 0, 0, item.width, item.height);  });});

上面的關鍵代碼是:

item.style.order = random[i];

通過將數字打亂順序,隨機賦值給每個canvas元素的order屬性,這樣瀏覽器就自動幫你排序了。
關於代碼的其他細節就不講了,這裡說一下怎樣交換兩張圖片的位置,真是出乎意料的簡單:

var order1 = item.style.order;var order2 = target.style.order;

只需要交換雙方的order屬性值就可以了。

完整代碼

<!DOCTYPE html><html><head lang="en">  <meta charset="UTF-8">  <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport" />  <meta content="yes" name="apple-mobile-web-app-capable" />  <meta content="black" name="apple-mobile-web-app-status-bar-style" />  <meta content="telephone=no" name="format-detection" />  <title></title>  <style>    html, body {      height: 100%;    }    body {      margin: 0;      padding: 0;      overflow: hidden;    }    .wrap {      display: flex;      flex-wrap: wrap;      width: 100%;      height: 100%;      overflow: hidden;    }    .wrap canvas {      width: 33.3333%;      height: 33.3333%;      border: 1px solid red;      box-sizing: border-box;    }  </style></head><body><div class="wrap">  <canvas data-value="1"></canvas>  <canvas data-value="2"></canvas>  <canvas data-value="3"></canvas>  <canvas data-value="4"></canvas>  <canvas data-value="5"></canvas>  <canvas data-value="6"></canvas>  <canvas data-value="7"></canvas>  <canvas data-value="8"></canvas>  <canvas data-value="9"></canvas></div><script>  var $ = function (el) {    return document.querySelector(el);  };  var touchMove, touchEnd;  var drawImage = function (url) {    return new Promise(function (resolve, reject) {      var img = new Image();      img.onload = function () {        resolve(img);      };      img.src = url;    })  };  drawImage("2.jpg").then(function (img) {    var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];    var random = arr.sort(function() {return Math.random() > 0.5});    [].forEach.call(document.querySelectorAll("canvas"), function (item, i) {      item.width = $(".wrap").clientWidth / 3;      item.height = $(".wrap").clientHeight / 3;      item.style.order = random[i];      var ctx = item.getContext("2d");      ctx.drawImage(img, img.width * (i % 3) / 3, img.height * Math.floor(i / 3) / 3, img.width / 3, img.height / 3, 0, 0, item.width, item.height);    });  });  document.addEventListener("touchstart", function (e) {    var target = e.target;    if (e.target.tagName.toLowerCase() !== "canvas") {      return;    }    var ctx = target.getContext("2d");    var image = ctx.getImageData(0, 0, target.width, target.height);    var obj = target.cloneNode(true);    obj.getContext("2d").putImageData(image, 0, 0);    var top = target.getBoundingClientRect().top, left = target.getBoundingClientRect().left;    obj.style.cssText = "position: absolute; top: " + top + "px; left: " + left + "px";    document.body.appendChild(obj);    var point = {"x": e.touches[0].pageX, "y": e.touches[0].pageY};    document.addEventListener("touchmove", touchMove = function (e) {      obj.style.cssText = "position: absolute; top:" + (e.touches[0].pageY - point.y + top) + "px; left: " + (e.touches[0].pageX - point.x + left) + "px";    });    document.addEventListener("touchend", touchEnd = function (e) {      var pos = {"x": e.changedTouches[0].pageX, "y": e.changedTouches[0].pageY};      [].forEach.call(document.querySelectorAll(".wrap canvas"), function (item, i) {        var offset = item.getBoundingClientRect();        if (pos.x > offset.left && pos.x < (offset.left + item.width) && pos.y > offset.top && pos.y < (offset.top + item.height)) {          var order1 = item.style.order;          var order2 = target.style.order;          if (obj.parentNode) {            document.body.removeChild(obj);          }          item.style.order = order2;          target.style.order = order1;        }      });      document.removeEventListener("touchmove", touchMove);      document.removeEventListener("touchend", touchEnd);    })  })</script></body></html>

大家做測試的時候,最好用Google模擬器或者手機開啟,因為只支援移動端觸摸事件。

代碼中只實現了準系統,並沒有實現完整功能。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.