本文实例讲述了html5版canvas自由拼图的实现方法。分享给大家供大家参考。具体方法如下:
代码运行效果如下图所示:
canvaselement.js代码如下:
复制代码
代码如下:
define('canvaselement', [ '../multi_upload/core' ], function(s) {
var canvas = window.canvas || {};
(function () {
    canvas.element = function() {};    
    canvas.element.prototype.fillbackground = true;
    canvas.element.prototype.showcorners = false;
    canvas.element.prototype.photoborder = true;
    canvas.element.prototype.polaroid = false;
    canvas.element.prototype._backgroundimg = null;
    canvas.element.prototype._groupselector = null;
    canvas.element.prototype._aimages = null;
    canvas.element.prototype._ocontext = null;
    canvas.element.prototype._oelement = null;
    canvas.element.prototype._oconfig = null;
    canvas.element.prototype._currenttransform = null;
    canvas.element.prototype._prevtransform = null;
    canvas.element.prototype.curangle = null;
    canvas.element.prototype.init = function(el, oconfig) {
        if (el == '') {
            return;
        }
        this._initelement(el);
        this._initconfig(oconfig);
        this._createcanvasbackground();
        this._createcontainer();
        this._initevents();
        this._initcustomevents();
    };
    canvas.element.prototype._initelement = function(el) {
        this._oelement = document.getelementbyid(el);
        this._ocontexttop = this._oelement.getcontext('2d');
    };
    canvas.element.prototype._initcustomevents = function() {
        this.onrotatestart = new canvas.customevent('onrotatestart');
        this.onrotatemove = new canvas.customevent('onrotatemove');        
        this.onrotatecomplete = new canvas.customevent('onrotatecomplete');
        this.ondragstart = new canvas.customevent('ondragstart');    
        this.ondragmove = new canvas.customevent('ondragmove');
        this.ondragcomplete = new canvas.customevent('ondragcomplete');
    };
    canvas.element.prototype._initconfig = function(oconfig) {
        this._oconfig = oconfig;
        this._oelement.width = this._oconfig.width;
        this._oelement.height = this._oconfig.height;
        this._oelement.style.width = this._oconfig.width + 'px';
        this._oelement.style.height = this._oconfig.height + 'px';
    };
    canvas.element.prototype._initevents = function() {
        var _this=this;
        s(this._oelement).on('mousedown',function(e){
             _this.onmousedown(e);
        });
        s(this._oelement).on( 'mouseup', function(e){
            _this.onmouseup(e);
        });
        s(this._oelement).on('mousemove', function(e){
            _this.onmousemove(e);
        });
    };
    canvas.element.prototype._createcontainer = function() {
        var canvasel = document.createelement('canvas');
        canvasel.id = this._oelement.id + '-canvas-container';
        var ocontainer = this._oelement.parentnode.insertbefore(canvasel, this._oelement);
        ocontainer.width = this._oconfig.width;
        ocontainer.height = this._oconfig.height;
        ocontainer.style.width = this._oconfig.width + 'px';
        ocontainer.style.height = this._oconfig.height + 'px';
        this._ocontextcontainer = ocontainer.getcontext('2d'); 
    };
    canvas.element.prototype._createcanvasbackground = function() {
        var canvasel = document.createelement('canvas');
        canvasel.id = this._oelement.id + '-canvas-background';
        var obackground = this._oelement.parentnode.insertbefore(canvasel, this._oelement);
        obackground.width = this._oconfig.width;
        obackground.height = this._oconfig.height;
        obackground.style.width = this._oconfig.width + 'px';
        obackground.style.height = this._oconfig.height + 'px';
        this._ocontextbackground = obackground.getcontext('2d'); 
    };
    canvas.element.prototype.setcanvasbackground = function(oimg) {
        this._backgroundimg = oimg;
        var originalimgsize = oimg.getoriginalsize();
        this._ocontextbackground.drawimage(oimg._oelement, 0, 0, originalimgsize.width, originalimgsize.height);
    };
    canvas.element.prototype.onmouseup = function(e) {
        if (this._aimages == null) {
            return;
        }
        if (this._currenttransform) {
            this._currenttransform.target.setimagecoords();
        }
        if (this._currenttransform != null && this._currenttransform.action == rotate) {
            this.onrotatecomplete.fire(e);
        } else if (this._currenttransform != null && this._currenttransform.action == drag) {
            this.ondragcomplete.fire(e);
        }
        this._currenttransform = null;
        this._groupselector = null;
        this.rendertop();
    };
    canvas.element.prototype.onmousedown = function(e) {
        var mp = this.findmouseposition(e);
        if (this._currenttransform != null || this._aimages == null) {
            return;
        }
        var oimg = this.findtargetimage(mp, false);
        if (!oimg) {
            this._groupselector = { ex: mp.ex, ey: mp.ey,
                                     top: 0, left: 0 };
        }
        else { 
            var action = (!this.findtargetcorner(mp, oimg)) ? 'drag' : 'rotate';
            if (action == rotate) {
                this.onrotatemove.fire(e);
            } else if (action == drag) {
                this.ondragmove.fire(e);
            }
            this._prevtransform=this._currenttransform = { 
                target: oimg,
                action: action,
                scalex: oimg.scalex,
                offsetx: mp.ex - oimg.left,
                offsety: mp.ey - oimg.top,
                ex: mp.ex, ey: mp.ey,
                left: oimg.left, top: oimg.top,
                theta: oimg.theta 
            };
            $('canvas_menu').style.transform='rotate('+oimg.theta*180/3.14+'deg)';
            $('canvas_menu').style.left=oimg.left+px;
            $('canvas_menu').style.top=oimg.top+px;
            $('canvas_menu').style.display=block;
            this.renderall(false,false);
        }
    };
    canvas.element.prototype.onmousemove = function(e) {
        var mp = this.findmouseposition(e);
        if (this._aimages == null) {
            return;
        }
        if (this._groupselector != null) {
            this._groupselector.left = mp.ex - this._groupselector.ex;
            this._groupselector.top = mp.ey - this._groupselector.ey;
            this.rendertop();
        }
        else if (this._currenttransform == null) {
            var targetimg = this.findtargetimage(mp, true);
            this.setcursor(mp, targetimg);
        }
        else {
            if (this._currenttransform.action == 'rotate') {
                this.rotateimage(mp);
                this.scaleimage(mp);
                this.onrotatemove.fire(e);
            }        
            else {
                this.translateimage(mp);
                this.ondragmove.fire(e);
            }
            this.rendertop();
        }        
    };
    canvas.element.prototype.translateimage = function(mp) {
        this._currenttransform.target.left = mp.ex - this._currenttransform.offsetx;
        this._currenttransform.target.top = mp.ey - this._currenttransform.offsety;
        $('canvas_menu').style.left=this._currenttransform.target.left+px;
        $('canvas_menu').style.top=this._currenttransform.target.top +px;
    };
    canvas.element.prototype.scaleimage = function(mp) {
        var lastlen = 
            math.sqrt(math.pow(this._currenttransform.ey - this._currenttransform.top, 2) +
            math.pow(this._currenttransform.ex - this._currenttransform.left, 2));
        var curlen = 
            math.sqrt(math.pow(mp.ey - this._currenttransform.top, 2) +
            math.pow(mp.ex - this._currenttransform.left, 2));
        var curscalex= this._currenttransform.scalex * (curlen / lastlen);
        var curscaley=this._currenttransform.target.scalex;
        if(curscalex>0.7&&curscaley>0.7){
            this._currenttransform.target.scalex =curscalex;
            this._currenttransform.target.scaley = curscaley;
        }
    };
    canvas.element.prototype.rotateimage = function(mp) {
        var lastangle = math.atan2(
                this._currenttransform.ey - this._currenttransform.top,
                this._currenttransform.ex - this._currenttransform.left
        );
var curangle = math.atan2(
            mp.ey - this._currenttransform.top,
            mp.ex - this._currenttransform.left
        );
        this._currenttransform.target.theta = (curangle - lastangle) + this._currenttransform.theta;
        this.curangle=this._currenttransform.target.theta*180/3.14;
        $('canvas_menu').style.transform='rotate('+this.curangle+'deg)';
    };
    canvas.element.prototype.setcursor = function(mp, targetimg) {
        if (!targetimg) {
            this._oelement.style.cursor = 'default';
        }
        else { 
            var corner = this.findtargetcorner(mp, targetimg);
            if (!corner) 
            {
                this._oelement.style.cursor = 'default';
            }
            else
            {
                if(corner == 'tr') {
                    this._oelement.style.cursor = 'ne-resize';
                }
                else if(corner == 'br') {
                    this._oelement.style.cursor = 'se-resize';
                }
                else if(corner == 'bl') {
                    this._oelement.style.cursor = 'sw-resize';
                }
                else if(corner == 'tl') {
                    this._oelement.style.cursor = 'nw-resize';
                }                                    
                else {
                    this._oelement.style.cursor = 'default';
                }
            }
        }
    };
    canvas.element.prototype.addimage = function(oimg) {
        if(s.isemptyobject(this._aimages)) {
            this._aimages = [];
        }
        this._aimages.push(oimg);
        this.renderall(false,true);    };
    canvas.element.prototype.renderall = function(allontop,allowcorners) {
        var containercanvas = (allontop) ? this._ocontexttop : this._ocontextcontainer;
        this._ocontexttop.clearrect(0,0,parseint(this._oconfig.width), parseint(this._oconfig.height));
        containercanvas.clearrect(0,0,parseint(this._oconfig.width), parseint(this._oconfig.height));
        if (allontop) {
            var originalimgsize = this._backgroundimg.getoriginalsize();
            this._ocontexttop.drawimage(this._backgroundimg._oelement, 0, 0, originalimgsize.width, originalimgsize.height);
        }
            for (var i = 0, l = this._aimages.length-1; i                 this.drawimageelement(containercanvas, this._aimages[i],allowcorners);            
            }
            this.drawimageelement(this._ocontexttop, this._aimages[this._aimages.length-1],allowcorners);
    };
    canvas.element.prototype.rendertop = function() {
        this._ocontexttop.clearrect(0,0,parseint(this._oconfig.width), parseint(this._oconfig.height));
        this.drawimageelement(this._ocontexttop, this._aimages[this._aimages.length-1],true);
        if (this._groupselector != null) {
            this._ocontexttop.fillstyle = rgba(0, 0, 200, 0.5);
            this._ocontexttop.fillrect(
                this._groupselector.ex - ((this._groupselector.left > 0) ?
                    0 : - this._groupselector.left), 
                this._groupselector.ey - ((this._groupselector.top > 0) ? 
                    0 : - this._groupselector.top), 
                math.abs(this._groupselector.left), 
                math.abs(this._groupselector.top)
            );
            this._ocontexttop.strokerect(
                this._groupselector.ex - ((this._groupselector.left > 0) ? 
                    0 : math.abs(this._groupselector.left)), 
                this._groupselector.ey - ((this._groupselector.top > 0) ? 
                    0 : math.abs(this._groupselector.top)), 
                math.abs(this._groupselector.left), 
                math.abs(this._groupselector.top)
            );
        }
    };
    canvas.element.prototype.drawimageelement = function(context, oimg,allowcorners) {
        oimg.cornervisibility=allowcorners;
        var offsety = oimg.height / 2;
        var offsetx = oimg.width / 2;
        context.save();
        context.translate(oimg.left, oimg.top);
        context.rotate(oimg.theta);
        context.scale(oimg.scalex, oimg.scaley);
        this.drawborder(context, oimg, offsetx, offsety);
        var originalimgsize = oimg.getoriginalsize();
        var polaroidheight = ((oimg.height - originalimgsize.height) - (oimg.width - originalimgsize.width))/2;
        context.drawimage(
            oimg._oelement, 
            - originalimgsize.width/2,  
            ((- originalimgsize.height)/2 - polaroidheight), 
            originalimgsize.width, 
            originalimgsize.height
        );
        if (oimg.cornervisibility) {
            this.drawcorners(context, oimg, offsetx, offsety);
        }
        context.restore();
    };
    canvas.element.prototype._getimagelines = function(ocoords) {
        return {
            topline: { 
                o: ocoords.tl,
                d: ocoords.tr 
            },
            rightline: { 
                o: ocoords.tr,
                d: ocoords.br 
            },
            bottomline: { 
                o: ocoords.br,
                d: ocoords.bl 
            },
            leftline: { 
                o: ocoords.bl,
                d: ocoords.tl 
            }
        };
    };
    canvas.element.prototype.findtargetimage = function(mp, hovering) {
        for (var i = this._aimages.length-1; i >= 0; i -= 1) {
            var ilines = this._getimagelines(this._aimages[i].ocoords);
            var xpoints = this._findcrosspoints(mp, ilines);
            if (xpoints % 2 == 1 && xpoints != 0) {
                var target = this._aimages[i];
                if (!hovering) {
                    this._aimages.splice(i, 1);
                    this._aimages.push(target);
                }
                return target;
            }
        }
        return false;
    };    
    canvas.element.prototype._findcrosspoints = function(mp, ocoords) {
        var b1, b2, a1, a2, xi, yi;
        var xcount = 0;
        var iline = null;
        for (linekey in ocoords) {
            iline = ocoords[linekey];
            if ((iline.o.y                 continue;
            }
            if ((iline.o.y >= mp.ey) && (iline.d.y >= mp.ey)) {
                continue;
            }
            if ((iline.o.x == iline.d.x) && (iline.o.x >= mp.ex)) { 
                xi = iline.o.x;
                yi = mp.ey;
            }
            else {
                b1 = 0; 
                b2 = (iline.d.y-iline.o.y)/(iline.d.x-iline.o.x); 
                a1 = mp.ey-b1*mp.ex;
                a2 = iline.o.y-b2*iline.o.x;
                xi = - (a1-a2)/(b1-b2); 
                yi = a1+b1*xi; 
            }
            if (xi >= mp.ex) { 
                xcount += 1;
            }
            if (xcount == 2) {
                break;
            }
        }
        return xcount;
    };
    canvas.element.prototype.findtargetcorner = function(mp, oimg) {
        var xpoints = null;
        var corners = ['tl','tr','br','bl'];
        for (var i in oimg.ocoords) {
            xpoints = this._findcrosspoints(mp, this._getimagelines(oimg.ocoords[i].corner));
            if (xpoints % 2 == 1 && xpoints != 0) {
                return i;
            }        
        }
        return false;
    };
    canvas.element.prototype.findmouseposition = function(e) {
        var parentnode = (e.srcelement) ? e.srcelement.parentnode : e.target.parentnode;
        var issafari2 = !s.support.ie&&!s.support.firefox;
        var scrollleft = document.documentelement.scrollleft || document.body.scrollleft;
        var scrolltop = document.documentelement.scrolltop || document.body.scrolltop;
        var safarioffsetleft = (issafari2) ? e.target.ownerdocument.body.offsetleft + scrollleft : 0;
        var safarioffsettop = (issafari2) ? e.target.ownerdocument.body.offsettop + scrolltop : 0;
        return {
            ex: e.clientx + scrollleft - parentnode.offsetleft - safarioffsetleft,
            ey: e.clienty + scrolltop - parentnode.offsettop - safarioffsettop,
            screenx: e.screenx,
            screeny: e.screeny
        };
    };
    canvas.element.prototype.drawborder = function(context, oimg, offsetx, offsety) {
        var outlinewidth = 2;
        context.fillstyle = 'rgba(0, 0, 0, .3)';
        context.fillrect(-2 - offsetx, -2 - offsety, oimg.width + (2 * outlinewidth), oimg.height + (2 * outlinewidth));
        context.fillstyle = '#fff';
        context.fillrect(-offsetx, -offsety, oimg.width, oimg.height);
    };
    canvas.element.prototype.drawcorners = function(context, oimg, offsetx, offsety) {
        context.fillstyle = rgba(0, 200, 50, 0.5);
        context.fillrect(-offsetx, -offsety, oimg.cornersize, oimg.cornersize);
        context.fillrect(oimg.width - offsetx - oimg.cornersize, -offsety, oimg.cornersize, oimg.cornersize);
        context.fillrect(-offsetx, oimg.height - offsety - oimg.cornersize, oimg.cornersize, oimg.cornersize);
        context.fillrect(oimg.width - offsetx - oimg.cornersize, oimg.height - offsety - oimg.cornersize, oimg.cornersize, oimg.cornersize);
    };
    canvas.element.prototype.clearcorners = function(context, oimg, offsetx, offsety) {
        context.clearrect(-offsetx, -offsety, oimg.cornersize, oimg.cornersize);
        context.clearrect(oimg.width - offsetx - oimg.cornersize, -offsety, oimg.cornersize, oimg.cornersize);
        context.clearrect(-offsetx, oimg.height - offsety - oimg.cornersize, oimg.cornersize, oimg.cornersize);
        context.clearrect(oimg.width - offsetx - oimg.cornersize, oimg.height - offsety - oimg.cornersize, oimg.cornersize, oimg.cornersize);
        context.restore();
    };
    canvas.element.prototype.canvasto = function(format) {
        this.renderall(true,false);
        var containercanvas =this._ocontexttop;
        for (var i = 0, l = this._aimages.length; i             var offsety = this._aimages[i].height / 2;
            var offsetx = this._aimages[i].width / 2;
            this.clearcorners(containercanvas, this._aimages[i], offsetx, offsety);
        }
        if (format == 'jpeg' || format == 'png') {
            return this._oelement.todataurl('image/'+format);
        }
    };    
    canvas.customevent = function(type) {
        this.type = type;
        this.scope = null;
        this.handler = null;
        var self = this;
        this.fire = function(e) {
            if(this.handler != null) {
                self.handler.call(self.scope, e);
            }
        };
    };    
}());
return canvas;
});
canvasimg.js代码如下:
复制代码
代码如下:
define('canvasimg', [ '../multi_upload/core' ], function(s) {
var canvas = window.canvas || {};
(function () {
    canvas.img = function(el, oconfig) {
        this._initelement(el);
        this._initconfig(oconfig);
        this.setimagecoords();
    };
    canvas.img.css_canvas = canvas-img;
    var default_config = {    
        top: { 
            key: top, 
            value: 10 
        },
        left: { 
            key: left, 
            value: 10
        },        
        angle: { 
            key: angle, 
            value: 0  
        },
        theta: { 
            key: theta, 
            value: 0  
        },
        scale-x: { 
            key: scalex, 
            value: 1
        },
        scale-y: { 
            key: scaley, 
            value: 1
        },
        cornersize: { 
            key: cornersize, 
            value:10
        },
        borderwidth: { 
            key: borderwidth, 
            value: 10
        },
        polaroidheight: {
            key: polaroidheight,
            value: 40
        },
        randomposition: {
            key: randomposition,
            value: true
        }
    };
    canvas.img.prototype._oelement = null;
    canvas.img.prototype.top = null;
    canvas.img.prototype.left = null;
    canvas.img.prototype.maxwidth = null;
    canvas.img.prototype.maxheight = null;
    canvas.img.prototype.ocoords = null;
    canvas.img.prototype.angle = null;
    canvas.img.prototype.theta = null;
    canvas.img.prototype.scalex = null;
    canvas.img.prototype.scaley = null;
    canvas.img.prototype.cornersize = null;
    canvas.img.prototype.polaroidheight = null;
    canvas.img.prototype.randomposition = null;
    canvas.img.prototype.selected = false;
    canvas.img.prototype.bordervisibility = false;
    canvas.img.prototype.cornervisibility = false;
    canvas.img.prototype._initelement = function(el) {
            this._oelement = el;
    };
    canvas.img.prototype._initconfig = function(oconfig) {
        var skey;
        for (skey in default_config) {
            var defaultkey = default_config[skey].key;
            if (!oconfig.hasownproperty(defaultkey)) { // = !(defaultkey in oconfig)
                this[defaultkey] = default_config[skey].value;
            }
            else {
                this[defaultkey] = oconfig[defaultkey];
            }
        }
        if (this.bordervisibility) {
            this.currentborder = this.borderwidth;
        }
        else {
            this.currentborder = 0;
        }
        var normalizedsize = this.getnormalizedsize(this._oelement, parseint(oconfig.maxwidth), parseint(oconfig.maxheight));
        this._oelement.width = normalizedsize.width;
        this._oelement.height = normalizedsize.height;
        this.width = normalizedsize.width + (2 * this.currentborder);
        this.height = normalizedsize.height + (2 * this.currentborder);
        if (this.randomposition) {
            this._setrandomproperties(oconfig);
        }
        this.theta = this.angle * (math.pi/180);
    };
    canvas.img.prototype.getnormalizedsize = function(oimg, maxwidth, maxheight) {
        if (maxheight && maxwidth && (oimg.width > oimg.height && (oimg.width / oimg.height)             normalizedwidth = math.floor((oimg.width * maxheight) / oimg.height);
            normalizedheight = maxheight;
        }
        else if (maxheight && ((oimg.height == oimg.width) || (oimg.height > oimg.width) || (oimg.height > maxheight))) {
            normalizedwidth = math.floor((oimg.width * maxheight) / oimg.height);
            normalizedheight = maxheight;
        }
        else if (maxwidth && (maxwidth             normalizedheight = math.floor((oimg.height * maxwidth) / oimg.width);
            normalizedwidth = maxwidth;
        }
        else {
            normalizedwidth = oimg.width;
            normalizedheight = oimg.height;            
        }
        return { width: normalizedwidth, height: normalizedheight }
    },
    canvas.img.prototype.getoriginalsize = function() {
        return { width: this._oelement.width, height: this._oelement.height }
    };
    canvas.img.prototype._setrandomproperties = function(oconfig) {
        if (oconfig.angle == null) {
            this.angle = (math.random() * 90);
        }
        if (oconfig.top == null) {
            this.top = this.height / 2 + math.random() * 450;
        }
        if (oconfig.left == null) {
            this.left = this.width / 2 + math.random() * 600;
        }
    };
    canvas.img.prototype.setcornersvisibility = function(visible) {
        this.cornervisibility = visible;
    };
    canvas.img.prototype.setimagecoords = function() {
        this.left = parseint(this.left);
        this.top = parseint(this.top);
        this.currentwidth = parseint(this.width) * this.scalex;
        this.currentheight = parseint(this.height) * this.scalex;
        this._hypotenuse = math.sqrt(math.pow(this.currentwidth / 2, 2) + math.pow(this.currentheight / 2, 2));
        this._angle = math.atan(this.currentheight / this.currentwidth);
        var offsetx = math.cos(this._angle + this.theta) * this._hypotenuse;
        var offsety = math.sin(this._angle + this.theta) * this._hypotenuse;
        var theta = this.theta;
        var sinth = math.sin(theta);
        var costh = math.cos(theta);
        var tl = {
            x: this.left - offsetx,
            y: this.top - offsety
        };
        var tr = {
            x: tl.x + (this.currentwidth * costh),
            y: tl.y + (this.currentwidth * sinth)
        };
        var br = {
            x: tr.x - (this.currentheight * sinth),
            y: tr.y + (this.currentheight * costh)
        };
        var bl = {
            x: tl.x - (this.currentheight * sinth),
            y: tl.y + (this.currentheight * costh)
        };
        this.ocoords = { tl: tl, tr: tr, br: br, bl: bl };
        this.setcornercoords();            
    };
    canvas.img.prototype.setcornercoords = function() {
        var coords = this.ocoords;
        var theta = this.theta;
        var cosoffset = this.cornersize * this.scalex * math.cos(theta);
        var sinoffset = this.cornersize * this.scalex * math.sin(theta);
        coords.tl.corner = {
            tl: {
                x: coords.tl.x,
                y: coords.tl.y
            },
            tr: {
                x: coords.tl.x + cosoffset,
                y: coords.tl.y + sinoffset
            },
            bl: {
                x: coords.tl.x - sinoffset,
                y: coords.tl.y + cosoffset
            }
        };
        coords.tl.corner.br = {
            x: coords.tl.corner.tr.x - sinoffset,
            y: coords.tl.corner.tr.y + cosoffset
        };
coords.tr.corner = {
            tl: {
                x: coords.tr.x - cosoffset,
                y: coords.tr.y - sinoffset
            },
            tr: {
                x: coords.tr.x,
                y: coords.tr.y
            },
            br: {
                x: coords.tr.x - sinoffset,
                y: coords.tr.y + cosoffset
            }
        };
        coords.tr.corner.bl = {
            x: coords.tr.corner.tl.x - sinoffset,
            y: coords.tr.corner.tl.y + cosoffset
        };
coords.bl.corner = {
            tl: {
                x: coords.bl.x + sinoffset,
                y: coords.bl.y - cosoffset
            },
            bl: {
                x: coords.bl.x,
                y: coords.bl.y
            },
            br: {
                x: coords.bl.x + cosoffset,
                y: coords.bl.y + sinoffset
            }
        };
        coords.bl.corner.tr = {
            x: coords.bl.corner.br.x + sinoffset,
            y: coords.bl.corner.br.y - cosoffset
        };
coords.br.corner = {
            tr: {
                x: coords.br.x + sinoffset,
                y: coords.br.y - cosoffset
            },
            bl: {
                x: coords.br.x - cosoffset,
                y: coords.br.y - sinoffset
            },
            br: {
                x: coords.br.x,
                y: coords.br.y
            }
        };
        coords.br.corner.tl = {
            x: coords.br.corner.bl.x + sinoffset,
            y: coords.br.corner.bl.y - cosoffset
        };
    };
}());
    return canvas;
});
puzzle.html代码如下:
复制代码
代码如下:
insert title here
删除                         href='javascript:void(0)' id='photo_update'>更改图片
添加图片                type=file multiple= id='fileimage'>                  href='javascript:void(0)' id='upload_btn'>上传 点击图片可以旋转,拖拽,
                缩放哦!
html5_puzzle.css代码如下:
复制代码
代码如下:
@charset utf-8;#html5_puzzle {
    font-size: 0;
}
canvas {
    background-color: transparent;
    left: 0;
    position: absolute;
    top: 0;
}
.puzzle_column,#puzzle_left,#puzzle_right,#add_img {
    display: inline-block;
}
.puzzle_column li {
    display: block;
    margin: 5px;
    border: 1px solid #ffffff;
}
.puzzle_column li:hover {
    border: 1px solid #3b5998;
    cursor: pointer;
}
.puzzle_column {
    font-size: 0;
}
#puzzle_left,#puzzle_right {
    border: 1px solid #3b5998;
}
#puzzle_right,#puzzle_bottom a {
    font-size: 14px;
    margin: 10px 0 0 10px;
}
#puzzle_bottom {
    margin: 5px 0;
}
#puzzle_canvas img {
}
#puzzle_canvas {
    overflow: hidden;
    width: 600px;
    height: 450px;
    position: relative;
}
#add_img input {
    position: absolute;
    font-size: 100px;
    right: 0;
    top: 0;
    opacity: 0;
}
#add_img {
    position: relative;
    display: inline-block;
    background: #3b5998;
    border-radius: 4px;
    padding: 4px 12px;
    overflow: hidden;
    color: #ffffff;
}
#bg,#show_list {
    display: none;
}
#canvas_menu {
    border: 1px solid red;
    position: absolute;
    z-index: 5;
    top: 0;
    left: 0;
    display: none;
}
#canvas_menu a {
    display: inline-block;
}
#test_canvas {
    top: 700px;
}
html5_puzzle.js代码如下:
复制代码
代码如下:
require([ 'img_upload', '../puzzle/canvasimg', '../puzzle/canvaselement' ], function(
        s, canvasimg, canvaselement) {
    var img=[];
    var canvas = new canvaselement.element();
    canvas.init('canvid1', {
        width : 600,
        height : 450
    });
    s('.puzzle_column img').on('click',function(e){
        var index=this.getattribute('data-index');
        $('bg').onload = function() {
            var ctx=$('canvid1-canvas-background').getcontext('2d');
            ctx.clearrect(0, 0,600,450);
            img[0]=new canvasimg.img($('bg'), {});
            canvas.setcanvasbackground(img[0]);
        };
        $('bg').setattribute('src','medium_img/'+index+'.jpg');
        e.stoppropagation();
    });
    var canvasdemo = function() {
        return {
            init : function() {
                var img_list=dom.query('#puzzle_canvas img');
                img[0]=new canvasimg.img($('bg'), {});
                s.each(img_list,function(i,el){
                        el.setattribute('data-index',i);
                        img.push(new canvasimg.img(el, {}));
                        canvas.addimage(img[i+1]);
                });
                canvas.setcanvasbackground(img[0]);
                this.cornersvisible = (this.cornersvisible) ? false : true;
                this.modifyimages(function(image) {
                    image.setcornersvisibility(this.cornersvisible);
                });
            },
            modifyimages : function(fn) {
                for ( var i =0, l = canvas._aimages.length; i                     fn.call(this, canvas._aimages[i]);
                }
                canvas.renderall(false,false);
                s('#puzzle_canvas img').remove();
                img = [];
            }
        };
    }();
    function getcurimg(){
        var oimg=canvas._prevtransform.target;
        for(var i=0;i        if(canvas._aimages[i]._oelement.src==oimg._oelement.src){
            return i;
        }
        }
    }
    s('#photo_delete').on('click',function(e){
        var i=getcurimg();
        canvas._aimages.splice(i,1);
        canvas.renderall(true,true);
        $('canvas_menu').style.display=none;
    });
    s('#photo_update').on('click',function(e){
        $('test').click();
    });
    s('#test').on('change',function(e){
        var files = e.target.files || e.datatransfer.files;
        var reader = new filereader();
        reader.onload = (function() {
            return function(e) {
        var dataurl = e.target.result, canvas1 = document.queryselector('#test_canvas'), ctx = canvas1.getcontext('2d'), img = new image();
        img.onload = function(e) {
            if(img.width>200||img.height>200){
                var prop=math.min(200/img.width,200/img.height);
                img.width=img.width*prop;
                img.height=img.height*prop;
            }
            canvas1.width=img.width;
            canvas1.height=img.height;
            ctx.drawimage(img, 0, 0, img.width, img.height);
            s('#canvid1').html(s('#canvid1').html()+);
            var t = window.settimeout(function() {
                var i=getcurimg(),target=canvas._prevtransform.target;
                console.log(target);
                canvas._aimages[i]=new canvasimg.img(dom.query('#canvid1 img')[0], {
                    top:target.top,
                    left:target.left,
                    scalex:target.scalex,
                    scaley:target.scaley,
                    angle:canvas.curangle
                });
                canvas.rendertop();
                cleartimeout(t);
                s('#canvid1 img').remove();
            },1000);
        };
        img.src = dataurl;
            };
        })();
        reader.readasdataurl(files[0]);
    });
    s('#upload_btn').on('click',function(){
        var imgdata = canvas.canvasto('jpeg');
        var imgvalue = imgdata.substr(22);
        s.ajax({
            url : 'http://localhost/html5/upload1.php',
            type : 'post',
            data : {
                imgdata : imgvalue,
                file_name :'mix_img.jpeg'
            },
            datatype : 'text',
            success : function(data) {
                alert(s);
            }
        });
    });
});
至于用html5 input读取图片,这很简单就不贴出来了。
希望本文所述对大家的html5程序设计有所帮助。
   
 
   