javascript - 拼图出现如图情况

查看:90
本文介绍了javascript - 拼图出现如图情况的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

每个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 游戏中,任意三个小块进行三轮换是可复原的,关于这,我有一个十分简洁的证明,这里地方太小,写不下。 ^_^

这篇关于javascript - 拼图出现如图情况的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆