每个img并没有填充每个div.box,图片采用canvas剪切然后把url传给.box里的img属性,相关代码如下
//创建构造函数
function Jigsaw(wrap, url, size) {
this.wrap = wrap
this.url = url
this.size = size
this.boxWidth = wrapWidth / size
this.createBox()
this.createCanvas()
this.init()
this.render()
this.bind()
}
//创建格子
Jigsaw.prototype.createBox = function() {
wrap.empty()
for (var i = 0; i < this.size * this.size; i++) {
wrap.append('<div class="box"><img src=""></div>')
}
$('.box').width(this.boxWidth)
$('.box').height(this.boxWidth)
};
//创建画布
Jigsaw.prototype.createCanvas = function() {
var can = document.createElement('canvas');
/*can.setAttribute("id",'canvas')*/
can.id = 'canvas'
can.style.display = 'none';
can.width = this.boxWidth;
can.height = this.boxWidth;
document.body.appendChild(can);
};
// 渲染九宫格
Jigsaw.prototype.render = function() {
var index = 0;
for (var i = 0; i < this.size; i++) {
for (var j = 0; j < this.size; j++) {
this.box.eq(index).css({
top: i * this.boxWidth + 'px',
left: j * this.boxWidth + 'px'
});
index++;
}
}
var self = this
this.image.onload = function() {
self.w = self.image.width / self.size
self.randomImage();
}
this.image.src = this.url;
};
// 渲染图片
Jigsaw.prototype.randomImage = function() {
var self = this;
var index = 0;
for (var i = 0; i < this.size; i++) {
for (var j = 0; j < this.size; j++) {
self.ctx.drawImage(this.image, self.w * j, self.w * i, self.w, self.w, 0, 0, this.boxWidth, this.boxWidth);
self.box.eq(self.imgRandomArr[index]).find('img').attr({
'index': index,
'src': self.canvas.toDataURL('image/jpeg'),
'width': '100%',
'height': '100%'
})
index++;
}
}
};
....
-----------css---------------
* {
margin: 0;
padding: 0
}
#wrap {
border: 1px solid #CDCDCD;
position: relative;
margin: 20px auto;
background-color: #F4F4F4;
}
.box {
position: absolute;
cursor: pointer;
z-index: 0;
}
参考 http://picturepuzzle.sinaapp.com
凑巧若干年前我也做过一个类似的游戏,使用了十分精巧的“三轮换”快速打乱算法,使用 background-image css 实现图片的“切割”
15-puzzle 游戏中,任意三个小块进行三轮换是可复原的,关于这,我有一个十分简洁的证明,这里地方太小,写不下。 ^_^