//创建构造函数
function Jigsaw(url) {
this.url = url
this.createCanvas()
this.init()
this.render()
this.bind()
}
var url = 'head.jpg'
new Jigsaw(url)
function getImgURL() {
var imgURL = ''
var reader = new FileReader()
if (!reader) {
alert('你的浏览器不支持FileReader')
return
}
if (this.files && this.files[0]) {
reader.onload = function(e) {
imgURL = e.target.result;
new Jigsaw(imgURL)
};
reader.readAsDataURL(this.files[0]);
}
}
document.getElementById('selectPic').addEventListener('change',
getImgURL, false);
这是一个绘制拼图的构造函数,我在script中这样调用它:new Jigsaw(url)来绘制拼图,除了这样的方法还有什么办法来调用 Jigsaw(url),#selectPic是一个input标签
<input type="file" value="上传图片" id="selectPic" accept="image/*">
用来上传本地图片,上传之后的图片没办法交换,加断点调试是因为执行了两次鼠标抬起事件程序(up()),这是为什么,相关的代码如下
Jigsaw.prototype.bind = function() {
var self = this
var boxs = document.getElementsByClassName('box')
this.box.on('mousedown', function(ev) {
self.op = $(this)
self.down(ev)
})
for (var i = 0; i < boxs.length; i++) {
boxs[i].addEventListener('touchstart', function(ev) {
self.op = $(this)
self.down(ev)
})
}
/*boxs.addEventListener('touchstart', function(ev) {
self.op = $(this)
self.down(ev)
})*/
document.addEventListener('mousemove', function(ev) {
if (self.flag) {
self.move(ev)
}
})
document.addEventListener('touchmove', function(ev) {
if (self.flag) {
self.move(ev)
}
})
document.addEventListener('mouseup', function(ev) {
self.up()
})
document.addEventListener('touchend', function(ev) {
self.up()
})
};
Jigsaw.prototype.up = function() {
this.flag = false
var positionIndex = this.moveboxPosition(this.position);
if (positionIndex in this.imgArr) {
var html = this.op.html()
var html2 = this.box.eq(positionIndex).html()
this.box.eq(positionIndex).html(html)
this.op.html(html2)
}
this.op.css({
left: this.oriboxLeft + 'px',
top: this.oriboxTop + 'px',
zIndex: 0
})
this.check()
};
效果图如下