最近公司恰好有个活动是要作一版 html5的拼图小游戏,因而本身心血来潮,本身先实现了一把,也算是尝尝鲜了。下面就把大致的思路介绍一下,但愿你们均可以作出一款属于本身的拼图小游戏,必须是更炫酷,更好玩!来吧,你们一块儿加油。。。
咱们知道如今的拼图游戏都是由九张小图片依次排列组成的,就是相似九宫格那样。那么之前的作法就是咱们利用Photoshop这样的工具把原始大图【尺寸通常都是正方形的哦】切成九张小块的正方形小图,可是这种作法有点不灵活,若是咱们要更换图片的话,就得从新去切图,好麻烦。。。
不过不要紧,如今咱们有了canvas!利用canvas咱们能够很轻松的作到这些。核心代码以下:javascript
var image = new Image(); image.onload = function() { var index = 1; for (var i=0; i<3; i++) { for (var j=0; j<3; j++) { ctx.drawImage(image, 300*j, 300*i, 300, 300, 0, 0, 300, 300); $lis.eq(index-1).find('img').attr('src', canvas.toDataURL('image/jpeg')); index++; } } } //900x900 image.src = "shanlian.jpg";
这里的核心是利用了javascript数组的随机排序,核心代码以下:html
imgArr.sort(function(a, b) { return Math.random() - Math.random(); }); var index = 1; for (var i=0; i<3; i++) { for (var j=0; j<3; j++) { ctx.drawImage(image, 300*j, 300*i, 300, 300, 0, 0, 300, 300); $lis.eq(imgArr[index-1]-1).find('img').data('seq', index).attr('src', canvas.toDataURL('image/jpeg')); index++; } }
这里无非就是利用向左滑动,向右滑动这些去实现拼图的操做。核心代码以下:html5
//阻止手机上浏览器的弹性下拉。。。 $('body').on('touchstart', function(e) { e.preventDefault(); }); $lis.on('swipeLeft', function(e) { e.preventDefault(); var $this = $(this); var index = $this.index(); var html = $this.html(); var $prev = $this.prev(); if ($.inArray(index, [3, 6]) > -1 || $prev.size() <= 0) { return false; } $this.html($prev.html()); $prev.html(html); App.check(); }); $lis.on('swipeRight', function(e) { e.preventDefault(); var $this = $(this); var index = $this.index(); var html = $this.html(); var $next = $this.next(); if ($.inArray(index, [2, 5]) > -1 || $next.size() <= 0) { return false; } $this.html($next.html()); $next.html(html); App.check(); }); $lis.on('swipeUp', function(e) { e.preventDefault(); var $this = $(this); var html = $this.html(); var index = $this.index() - 3; var $up = $lis.eq(index); if (index >= 0 && $up.size() > 0) { $this.html($up.html()); $up.html(html); App.check(); } }); $lis.on('swipeDown', function(e) { e.preventDefault(); var $this = $(this); var html = $this.html(); var index = $this.index() + 3; var $down = $lis.eq(index); if (index < 9 && $down.size() > 0) { $this.html($down.html()); $down.html(html); App.check(); } });
这里的话,拼图顺序的每一次变化都要去检测一下是否完成了,原理就是获取当前小块图片的顺序和原始的图片进行比较。核心代码以下:java
var resArr = []; $('#gameBox img').each(function(k, v) { resArr.push(v.getAttribute("data-seq")); }); if (resArr.join("") === oriArr.join("")) { //完成的处理。。。 }
核心代码和思路就是上面这些,其实整个过程走下来仍是蛮简单的,接下来无非要作的就是再加一下花哨的东西了(时间,难度等级,排名等等)。若是你们感兴趣的话,完整版代码猛戳 这里 了。git