当canvas的鼠标click事件触发后

html5版canvas自由拼图,html5canvas拼图

效果:

图片 1

 

canvasElement.js

  1 define('canvasElement', [ '../multi_upload/core' ], function(S) {
  2 var Canvas = window.Canvas || {};
  3 (function () {
  4     Canvas.Element = function() {};    
  5     Canvas.Element.prototype.fillBackground = true;
  6     Canvas.Element.prototype.showcorners = false;
  7     Canvas.Element.prototype.photoborder = true;
  8     Canvas.Element.prototype.polaroid = false;
  9     Canvas.Element.prototype._backgroundImg = null;
 10     Canvas.Element.prototype._groupSelector = null;
 11     Canvas.Element.prototype._aImages = null;
 12     Canvas.Element.prototype._oContext = null;
 13     Canvas.Element.prototype._oElement = null;
 14     Canvas.Element.prototype._oConfig = null;
 15     Canvas.Element.prototype._currentTransform = null;
 16     Canvas.Element.prototype._prevTransform = null;
 17     Canvas.Element.prototype.curAngle = null;
 18     Canvas.Element.prototype.init = function(el, oConfig) {
 19         if (el == '') {
 20             return;
 21         }
 22         this._initElement(el);
 23         this._initConfig(oConfig);
 24         this._createCanvasBackground();
 25         this._createContainer();
 26         this._initEvents();
 27         this._initCustomEvents();
 28     };
 29     Canvas.Element.prototype._initElement = function(el) {
 30         this._oElement = document.getElementById(el);
 31         this._oContextTop = this._oElement.getContext('2d');
 32     };
 33     Canvas.Element.prototype._initCustomEvents = function() {
 34         this.onRotateStart = new Canvas.CustomEvent('onRotateStart');
 35         this.onRotateMove = new Canvas.CustomEvent('onRotateMove');        
 36         this.onRotateComplete = new Canvas.CustomEvent('onRotateComplete');
 37         this.onDragStart = new Canvas.CustomEvent('onDragStart');    
 38         this.onDragMove = new Canvas.CustomEvent('onDragMove');
 39         this.onDragComplete = new Canvas.CustomEvent('onDragComplete');
 40     };
 41     Canvas.Element.prototype._initConfig = function(oConfig) {
 42         this._oConfig = oConfig;
 43         this._oElement.width = this._oConfig.width;
 44         this._oElement.height = this._oConfig.height;
 45         this._oElement.style.width = this._oConfig.width + 'px';
 46         this._oElement.style.height = this._oConfig.height + 'px';
 47     };
 48     Canvas.Element.prototype._initEvents = function() {
 49         var _this=this;
 50         S(this._oElement).on('mousedown',function(e){
 51              _this.onMouseDown(e);
 52         });
 53         S(this._oElement).on( 'mouseup', function(e){
 54             _this.onMouseUp(e);
 55         });
 56         S(this._oElement).on('mousemove', function(e){
 57             _this.onMouseMove(e);
 58         });
 59     };
 60     Canvas.Element.prototype._createContainer = function() {
 61         var canvasEl = document.createElement('canvas');
 62         canvasEl.id = this._oElement.id + '-canvas-container';
 63         var oContainer = this._oElement.parentNode.insertBefore(canvasEl, this._oElement);
 64         oContainer.width = this._oConfig.width;
 65         oContainer.height = this._oConfig.height;
 66         oContainer.style.width = this._oConfig.width + 'px';
 67         oContainer.style.height = this._oConfig.height + 'px';
 68         this._oContextContainer = oContainer.getContext('2d'); 
 69     };
 70     Canvas.Element.prototype._createCanvasBackground = function() {
 71         var canvasEl = document.createElement('canvas');
 72         canvasEl.id = this._oElement.id + '-canvas-background';
 73         var oBackground = this._oElement.parentNode.insertBefore(canvasEl, this._oElement);
 74         oBackground.width = this._oConfig.width;
 75         oBackground.height = this._oConfig.height;
 76         oBackground.style.width = this._oConfig.width + 'px';
 77         oBackground.style.height = this._oConfig.height + 'px';
 78         this._oContextBackground = oBackground.getContext('2d'); 
 79     };
 80     Canvas.Element.prototype.setCanvasBackground = function(oImg) {
 81         this._backgroundImg = oImg;
 82         var originalImgSize = oImg.getOriginalSize();
 83         this._oContextBackground.drawImage(oImg._oElement, 0, 0, originalImgSize.width, originalImgSize.height);
 84     };
 85     Canvas.Element.prototype.onMouseUp = function(e) {
 86         if (this._aImages == null) {
 87             return;
 88         }
 89         if (this._currentTransform) {
 90             this._currentTransform.target.setImageCoords();
 91         }
 92         if (this._currentTransform != null && this._currentTransform.action == "rotate") {
 93             this.onRotateComplete.fire(e);
 94         } else if (this._currentTransform != null && this._currentTransform.action == "drag") {
 95             this.onDragComplete.fire(e);
 96         }
 97         this._currentTransform = null;
 98         this._groupSelector = null;
 99         this.renderTop();
100     };
101     Canvas.Element.prototype.onMouseDown = function(e) {
102         var mp = this.findMousePosition(e);
103         if (this._currentTransform != null || this._aImages == null) {
104             return;
105         }
106         var oImg = this.findTargetImage(mp, false);
107         if (!oImg) {
108             this._groupSelector = { ex: mp.ex, ey: mp.ey,
109                                      top: 0, left: 0 };
110         }
111         else { 
112             var action = (!this.findTargetCorner(mp, oImg)) ? 'drag' : 'rotate';
113             if (action == "rotate") {
114                 this.onRotateMove.fire(e);
115             } else if (action == "drag") {
116                 this.onDragMove.fire(e);
117             }
118             this._prevTransform=this._currentTransform = { 
119                 target: oImg,
120                 action: action,
121                 scalex: oImg.scalex,
122                 offsetX: mp.ex - oImg.left,
123                 offsetY: mp.ey - oImg.top,
124                 ex: mp.ex, ey: mp.ey,
125                 left: oImg.left, top: oImg.top,
126                 theta: oImg.theta 
127             };
128             $('canvas_menu').style.transform='rotate('+oImg.theta*180/3.14+'deg)';
129             $('canvas_menu').style.left=oImg.left+"px";
130             $('canvas_menu').style.top=oImg.top+"px";
131             $('canvas_menu').style.display="block";
132             this.renderAll(false,false);
133         }
134     };
135     Canvas.Element.prototype.onMouseMove = function(e) {
136         var mp = this.findMousePosition(e);
137         if (this._aImages == null) {
138             return;
139         }
140         if (this._groupSelector != null) {
141             this._groupSelector.left = mp.ex - this._groupSelector.ex;
142             this._groupSelector.top = mp.ey - this._groupSelector.ey;
143             this.renderTop();
144         }
145         else if (this._currentTransform == null) {
146             var targetImg = this.findTargetImage(mp, true);
147             this.setCursor(mp, targetImg);
148         }
149         else {
150             if (this._currentTransform.action == 'rotate') {
151                 this.rotateImage(mp);
152                 this.scaleImage(mp);
153                 this.onRotateMove.fire(e);
154             }        
155             else {
156                 this.translateImage(mp);
157                 this.onDragMove.fire(e);
158             }
159             this.renderTop();
160         }        
161     };
162     Canvas.Element.prototype.translateImage = function(mp) {
163         this._currentTransform.target.left = mp.ex - this._currentTransform.offsetX;
164         this._currentTransform.target.top = mp.ey - this._currentTransform.offsetY;
165         $('canvas_menu').style.left=this._currentTransform.target.left+"px";
166         $('canvas_menu').style.top=this._currentTransform.target.top +"px";
167     };
168     Canvas.Element.prototype.scaleImage = function(mp) {
169         var lastLen = 
170             Math.sqrt(Math.pow(this._currentTransform.ey - this._currentTransform.top, 2) +
171             Math.pow(this._currentTransform.ex - this._currentTransform.left, 2));
172         var curLen = 
173             Math.sqrt(Math.pow(mp.ey - this._currentTransform.top, 2) +
174             Math.pow(mp.ex - this._currentTransform.left, 2));
175         var curScalex= this._currentTransform.scalex * (curLen / lastLen);
176         var curScaley=this._currentTransform.target.scalex;
177         if(curScalex>0.7&&curScaley>0.7){
178             this._currentTransform.target.scalex =curScalex;
179             this._currentTransform.target.scaley = curScaley;
180         }
181     };
182     Canvas.Element.prototype.rotateImage = function(mp) {
183         var lastAngle = Math.atan2(
184                 this._currentTransform.ey - this._currentTransform.top,
185                 this._currentTransform.ex - this._currentTransform.left
186         );
187         
188         var curAngle = Math.atan2(
189             mp.ey - this._currentTransform.top,
190             mp.ex - this._currentTransform.left
191         );
192         this._currentTransform.target.theta = (curAngle - lastAngle) + this._currentTransform.theta;
193         this.curAngle=this._currentTransform.target.theta*180/3.14;
194         $('canvas_menu').style.transform='rotate('+this.curAngle+'deg)';
195     };
196     Canvas.Element.prototype.setCursor = function(mp, targetImg) {
197         if (!targetImg) {
198             this._oElement.style.cursor = 'default';
199         }
200         else { 
201             var corner = this.findTargetCorner(mp, targetImg);
202             if (!corner) 
203             {
204                 this._oElement.style.cursor = 'default';
205             }
206             else
207             {
208                 if(corner == 'tr') {
209                     this._oElement.style.cursor = 'ne-resize';
210                 }
211                 else if(corner == 'br') {
212                     this._oElement.style.cursor = 'se-resize';
213                 }
214                 else if(corner == 'bl') {
215                     this._oElement.style.cursor = 'sw-resize';
216                 }
217                 else if(corner == 'tl') {
218                     this._oElement.style.cursor = 'nw-resize';
219                 }                                    
220                 else {
221                     this._oElement.style.cursor = 'default';
222                 }
223             }
224         }
225     };
226     Canvas.Element.prototype.addImage = function(oImg) {
227         if(S.isEmptyObject(this._aImages)) {
228             this._aImages = [];
229         }
230         this._aImages.push(oImg);
231         this.renderAll(false,true);
232 
233     };
234     Canvas.Element.prototype.renderAll = function(allOnTop,allowCorners) {
235         var containerCanvas = (allOnTop) ? this._oContextTop : this._oContextContainer;
236         this._oContextTop.clearRect(0,0,parseInt(this._oConfig.width), parseInt(this._oConfig.height));
237         containerCanvas.clearRect(0,0,parseInt(this._oConfig.width), parseInt(this._oConfig.height));
238         if (allOnTop) {
239             var originalImgSize = this._backgroundImg.getOriginalSize();
240             this._oContextTop.drawImage(this._backgroundImg._oElement, 0, 0, originalImgSize.width, originalImgSize.height);
241         }
242             for (var i = 0, l = this._aImages.length-1; i < l; i += 1) {
243                 this.drawImageElement(containerCanvas, this._aImages[i],allowCorners);            
244             }
245             this.drawImageElement(this._oContextTop, this._aImages[this._aImages.length-1],allowCorners);
246     };
247     Canvas.Element.prototype.renderTop = function() {
248         this._oContextTop.clearRect(0,0,parseInt(this._oConfig.width), parseInt(this._oConfig.height));
249         this.drawImageElement(this._oContextTop, this._aImages[this._aImages.length-1],true);
250         if (this._groupSelector != null) {
251             this._oContextTop.fillStyle = "rgba(0, 0, 200, 0.5)";
252             this._oContextTop.fillRect(
253                 this._groupSelector.ex - ((this._groupSelector.left > 0) ?
254                     0 : - this._groupSelector.left), 
255                 this._groupSelector.ey - ((this._groupSelector.top > 0) ? 
256                     0 : - this._groupSelector.top), 
257                 Math.abs(this._groupSelector.left), 
258                 Math.abs(this._groupSelector.top)
259             );
260             this._oContextTop.strokeRect(
261                 this._groupSelector.ex - ((this._groupSelector.left > 0) ? 
262                     0 : Math.abs(this._groupSelector.left)), 
263                 this._groupSelector.ey - ((this._groupSelector.top > 0) ? 
264                     0 : Math.abs(this._groupSelector.top)), 
265                 Math.abs(this._groupSelector.left), 
266                 Math.abs(this._groupSelector.top)
267             );
268         }
269     };
270     Canvas.Element.prototype.drawImageElement = function(context, oImg,allowCorners) {
271         oImg.cornervisibility=allowCorners;
272         var offsetY = oImg.height / 2;
273         var offsetX = oImg.width / 2;
274         context.save();
275         context.translate(oImg.left, oImg.top);
276         context.rotate(oImg.theta);
277         context.scale(oImg.scalex, oImg.scaley);
278         this.drawBorder(context, oImg, offsetX, offsetY);
279         var originalImgSize = oImg.getOriginalSize();
280         var polaroidHeight = ((oImg.height - originalImgSize.height) - (oImg.width - originalImgSize.width))/2;
281         context.drawImage(
282             oImg._oElement, 
283             - originalImgSize.width/2,  
284             ((- originalImgSize.height)/2 - polaroidHeight), 
285             originalImgSize.width, 
286             originalImgSize.height
287         );
288         if (oImg.cornervisibility) {
289             this.drawCorners(context, oImg, offsetX, offsetY);
290         }
291         context.restore();
292     };
293     Canvas.Element.prototype._getImageLines = function(oCoords) {
294         return {
295             topline: { 
296                 o: oCoords.tl,
297                 d: oCoords.tr 
298             },
299             rightline: { 
300                 o: oCoords.tr,
301                 d: oCoords.br 
302             },
303             bottomline: { 
304                 o: oCoords.br,
305                 d: oCoords.bl 
306             },
307             leftline: { 
308                 o: oCoords.bl,
309                 d: oCoords.tl 
310             }
311         };
312     };
313     Canvas.Element.prototype.findTargetImage = function(mp, hovering) {
314         for (var i = this._aImages.length-1; i >= 0; i -= 1) {
315             var iLines = this._getImageLines(this._aImages[i].oCoords);
316             var xpoints = this._findCrossPoints(mp, iLines);
317             if (xpoints % 2 == 1 && xpoints != 0) {
318                 var target = this._aImages[i];
319                 if (!hovering) {
320                     this._aImages.splice(i, 1);
321                     this._aImages.push(target);
322                 }
323                 return target;
324             }
325         }
326         return false;
327     };    
328     Canvas.Element.prototype._findCrossPoints = function(mp, oCoords) {
329         var b1, b2, a1, a2, xi, yi;
330         var xcount = 0;
331         var iLine = null;
332         for (lineKey in oCoords) {
333             iLine = oCoords[lineKey];
334             if ((iLine.o.y < mp.ey) && (iLine.d.y < mp.ey)) {
335                 continue;
336             }
337             if ((iLine.o.y >= mp.ey) && (iLine.d.y >= mp.ey)) {
338                 continue;
339             }
340             if ((iLine.o.x == iLine.d.x) && (iLine.o.x >= mp.ex)) { 
341                 xi = iLine.o.x;
342                 yi = mp.ey;
343             }
344             else {
345                 b1 = 0; 
346                 b2 = (iLine.d.y-iLine.o.y)/(iLine.d.x-iLine.o.x); 
347                 a1 = mp.ey-b1*mp.ex;
348                 a2 = iLine.o.y-b2*iLine.o.x;
349                 xi = - (a1-a2)/(b1-b2); 
350                 yi = a1+b1*xi; 
351             }
352             if (xi >= mp.ex) { 
353                 xcount += 1;
354             }
355             if (xcount == 2) {
356                 break;
357             }
358         }
359         return xcount;
360     };
361     Canvas.Element.prototype.findTargetCorner = function(mp, oImg) {
362         var xpoints = null;
363         var corners = ['tl','tr','br','bl'];
364         for (var i in oImg.oCoords) {
365             xpoints = this._findCrossPoints(mp, this._getImageLines(oImg.oCoords[i].corner));
366             if (xpoints % 2 == 1 && xpoints != 0) {
367                 return i;
368             }        
369         }
370         return false;
371     };
372     Canvas.Element.prototype.findMousePosition = function(e) {
373         var parentNode = (e.srcElement) ? e.srcElement.parentNode : e.target.parentNode;
374         var isSafari2 = !S.support.ie&&!S.support.firefox;
375         var scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft;
376         var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
377         var safariOffsetLeft = (isSafari2) ? e.target.ownerDocument.body.offsetLeft + scrollLeft : 0;
378         var safariOffsetTop = (isSafari2) ? e.target.ownerDocument.body.offsetTop + scrollTop : 0;
379         return {
380             ex: e.clientX + scrollLeft - parentNode.offsetLeft - safariOffsetLeft,
381             ey: e.clientY + scrollTop - parentNode.offsetTop - safariOffsetTop,
382             screenX: e.screenX,
383             screenY: e.screenY
384         };
385     };
386     Canvas.Element.prototype.drawBorder = function(context, oImg, offsetX, offsetY) {
387         var outlinewidth = 2;
388         context.fillStyle = 'rgba(0, 0, 0, .3)';
389         context.fillRect(-2 - offsetX, -2 - offsetY, oImg.width + (2 * outlinewidth), oImg.height + (2 * outlinewidth));
390         context.fillStyle = '#fff';
391         context.fillRect(-offsetX, -offsetY, oImg.width, oImg.height);
392     };
393     Canvas.Element.prototype.drawCorners = function(context, oImg, offsetX, offsetY) {
394         context.fillStyle = "rgba(0, 200, 50, 0.5)";
395         context.fillRect(-offsetX, -offsetY, oImg.cornersize, oImg.cornersize);
396         context.fillRect(oImg.width - offsetX - oImg.cornersize, -offsetY, oImg.cornersize, oImg.cornersize);
397         context.fillRect(-offsetX, oImg.height - offsetY - oImg.cornersize, oImg.cornersize, oImg.cornersize);
398         context.fillRect(oImg.width - offsetX - oImg.cornersize, oImg.height - offsetY - oImg.cornersize, oImg.cornersize, oImg.cornersize);
399     };
400     Canvas.Element.prototype.clearCorners = function(context, oImg, offsetX, offsetY) {
401         context.clearRect(-offsetX, -offsetY, oImg.cornersize, oImg.cornersize);
402         context.clearRect(oImg.width - offsetX - oImg.cornersize, -offsetY, oImg.cornersize, oImg.cornersize);
403         context.clearRect(-offsetX, oImg.height - offsetY - oImg.cornersize, oImg.cornersize, oImg.cornersize);
404         context.clearRect(oImg.width - offsetX - oImg.cornersize, oImg.height - offsetY - oImg.cornersize, oImg.cornersize, oImg.cornersize);
405         context.restore();
406     };
407     Canvas.Element.prototype.canvasTo = function(format) {
408         this.renderAll(true,false);
409         var containerCanvas =this._oContextTop;
410         for (var i = 0, l = this._aImages.length; i < l; i += 1) {
411             var offsetY = this._aImages[i].height / 2;
412             var offsetX = this._aImages[i].width / 2;
413             this.clearCorners(containerCanvas, this._aImages[i], offsetX, offsetY);
414         }
415         if (format == 'jpeg' || format == 'png') {
416             return this._oElement.toDataURL('image/'+format);
417         }
418     };    
419     Canvas.CustomEvent = function(type) {
420         this.type = type;
421         this.scope = null;
422         this.handler = null;
423         var self = this;
424         this.fire = function(e) {
425             if(this.handler != null) {
426                 self.handler.call(self.scope, e);
427             }
428         };
429     };    
430 }());
431 return Canvas;
432 });

canvasImg.js

  1 define('canvasImg', [ '../multi_upload/core' ], function(S) {
  2 var Canvas = window.Canvas || {};
  3 (function () {
  4     Canvas.Img = function(el, oConfig) {
  5         this._initElement(el);
  6         this._initConfig(oConfig);
  7         this.setImageCoords();
  8     };
  9     Canvas.Img.CSS_CANVAS = "canvas-img";
 10     var DEFAULT_CONFIG = {    
 11         "TOP": { 
 12             key: "top", 
 13             value: 10 
 14         },
 15         "LEFT": { 
 16             key: "left", 
 17             value: 10
 18         },        
 19         "ANGLE": { 
 20             key: "angle", 
 21             value: 0  
 22         },
 23         "THETA": { 
 24             key: "theta", 
 25             value: 0  
 26         },
 27         "SCALE-X": { 
 28             key: "scalex", 
 29             value: 1
 30         },
 31         "SCALE-Y": { 
 32             key: "scaley", 
 33             value: 1
 34         },
 35         "CORNERSIZE": { 
 36             key: "cornersize", 
 37             value:10
 38         },
 39         "BORDERWIDTH": { 
 40             key: "borderwidth", 
 41             value: 10
 42         },
 43         "POLAROIDHEIGHT": {
 44             key: "polaroidheight",
 45             value: 40
 46         },
 47         "RANDOMPOSITION": {
 48             key: "randomposition",
 49             value: true
 50         }
 51     };
 52     Canvas.Img.prototype._oElement = null;
 53     Canvas.Img.prototype.top = null;
 54     Canvas.Img.prototype.left = null;
 55     Canvas.Img.prototype.maxwidth = null;
 56     Canvas.Img.prototype.maxheight = null;
 57     Canvas.Img.prototype.oCoords = null;
 58     Canvas.Img.prototype.angle = null;
 59     Canvas.Img.prototype.theta = null;
 60     Canvas.Img.prototype.scalex = null;
 61     Canvas.Img.prototype.scaley = null;
 62     Canvas.Img.prototype.cornersize = null;
 63     Canvas.Img.prototype.polaroidheight = null;
 64     Canvas.Img.prototype.randomposition = null;
 65     Canvas.Img.prototype.selected = false;
 66     Canvas.Img.prototype.bordervisibility = false;
 67     Canvas.Img.prototype.cornervisibility = false;
 68     Canvas.Img.prototype._initElement = function(el) {
 69             this._oElement = el;
 70     };
 71     Canvas.Img.prototype._initConfig = function(oConfig) {
 72         var sKey;
 73         for (sKey in DEFAULT_CONFIG) {
 74             var defaultKey = DEFAULT_CONFIG[sKey].key;
 75             if (!oConfig.hasOwnProperty(defaultKey)) { // = !(defaultKey in oConfig)
 76                 this[defaultKey] = DEFAULT_CONFIG[sKey].value;
 77             }
 78             else {
 79                 this[defaultKey] = oConfig[defaultKey];
 80             }
 81         }
 82         if (this.bordervisibility) {
 83             this.currentBorder = this.borderwidth;
 84         }
 85         else {
 86             this.currentBorder = 0;
 87         }
 88         var normalizedSize = this.getNormalizedSize(this._oElement, parseInt(oConfig.maxwidth), parseInt(oConfig.maxheight));
 89         this._oElement.width = normalizedSize.width;
 90         this._oElement.height = normalizedSize.height;
 91         this.width = normalizedSize.width + (2 * this.currentBorder);
 92         this.height = normalizedSize.height + (2 * this.currentBorder);
 93         if (this.randomposition) {
 94             this._setRandomProperties(oConfig);
 95         }
 96         this.theta = this.angle * (Math.PI/180);
 97     };
 98     Canvas.Img.prototype.getNormalizedSize = function(oImg, maxwidth, maxheight) {
 99         if (maxheight && maxwidth && (oImg.width > oImg.height && (oImg.width / oImg.height) < (maxwidth / maxheight))) {
100             normalizedWidth = Math.floor((oImg.width * maxheight) / oImg.height);
101             normalizedHeight = maxheight;
102         }
103         else if (maxheight && ((oImg.height == oImg.width) || (oImg.height > oImg.width) || (oImg.height > maxheight))) {
104             normalizedWidth = Math.floor((oImg.width * maxheight) / oImg.height);
105             normalizedHeight = maxheight;
106         }
107         else if (maxwidth && (maxwidth < oImg.width)){ 
108             normalizedHeight = Math.floor((oImg.height * maxwidth) / oImg.width);
109             normalizedWidth = maxwidth;
110         }
111         else {
112             normalizedWidth = oImg.width;
113             normalizedHeight = oImg.height;            
114         }
115         return { width: normalizedWidth, height: normalizedHeight }
116     },
117     Canvas.Img.prototype.getOriginalSize = function() {
118         return { width: this._oElement.width, height: this._oElement.height }
119     };
120     Canvas.Img.prototype._setRandomProperties = function(oConfig) {
121         if (oConfig.angle == null) {
122             this.angle = (Math.random() * 90);
123         }
124         if (oConfig.top == null) {
125             this.top = this.height / 2 + Math.random() * 450;
126         }
127         if (oConfig.left == null) {
128             this.left = this.width / 2 + Math.random() * 600;
129         }
130     };
131     Canvas.Img.prototype.setCornersVisibility = function(visible) {
132         this.cornervisibility = visible;
133     };
134     Canvas.Img.prototype.setImageCoords = function() {
135         this.left = parseInt(this.left);
136         this.top = parseInt(this.top);
137         this.currentWidth = parseInt(this.width) * this.scalex;
138         this.currentHeight = parseInt(this.height) * this.scalex;
139         this._hypotenuse = Math.sqrt(Math.pow(this.currentWidth / 2, 2) + Math.pow(this.currentHeight / 2, 2));
140         this._angle = Math.atan(this.currentHeight / this.currentWidth);
141         var offsetX = Math.cos(this._angle + this.theta) * this._hypotenuse;
142         var offsetY = Math.sin(this._angle + this.theta) * this._hypotenuse;
143         var theta = this.theta;
144         var sinTh = Math.sin(theta);
145         var cosTh = Math.cos(theta);
146         var tl = {
147             x: this.left - offsetX,
148             y: this.top - offsetY
149         };
150         var tr = {
151             x: tl.x + (this.currentWidth * cosTh),
152             y: tl.y + (this.currentWidth * sinTh)
153         };
154         var br = {
155             x: tr.x - (this.currentHeight * sinTh),
156             y: tr.y + (this.currentHeight * cosTh)
157         };
158         var bl = {
159             x: tl.x - (this.currentHeight * sinTh),
160             y: tl.y + (this.currentHeight * cosTh)
161         };
162         this.oCoords = { tl: tl, tr: tr, br: br, bl: bl };
163         this.setCornerCoords();            
164     };
165     Canvas.Img.prototype.setCornerCoords = function() {
166         var coords = this.oCoords;
167         var theta = this.theta;
168         var cosOffset = this.cornersize * this.scalex * Math.cos(theta);
169         var sinOffset = this.cornersize * this.scalex * Math.sin(theta);
170         coords.tl.corner = {
171             tl: {
172                 x: coords.tl.x,
173                 y: coords.tl.y
174             },
175             tr: {
176                 x: coords.tl.x + cosOffset,
177                 y: coords.tl.y + sinOffset
178             },
179             bl: {
180                 x: coords.tl.x - sinOffset,
181                 y: coords.tl.y + cosOffset
182             }
183         };
184         coords.tl.corner.br = {
185             x: coords.tl.corner.tr.x - sinOffset,
186             y: coords.tl.corner.tr.y + cosOffset
187         };
188         
189         coords.tr.corner = {
190             tl: {
191                 x: coords.tr.x - cosOffset,
192                 y: coords.tr.y - sinOffset
193             },
194             tr: {
195                 x: coords.tr.x,
196                 y: coords.tr.y
197             },
198             br: {
199                 x: coords.tr.x - sinOffset,
200                 y: coords.tr.y + cosOffset
201             }
202         };
203         coords.tr.corner.bl = {
204             x: coords.tr.corner.tl.x - sinOffset,
205             y: coords.tr.corner.tl.y + cosOffset
206         };
207         
208         coords.bl.corner = {
209             tl: {
210                 x: coords.bl.x + sinOffset,
211                 y: coords.bl.y - cosOffset
212             },
213             bl: {
214                 x: coords.bl.x,
215                 y: coords.bl.y
216             },
217             br: {
218                 x: coords.bl.x + cosOffset,
219                 y: coords.bl.y + sinOffset
220             }
221         };
222         coords.bl.corner.tr = {
223             x: coords.bl.corner.br.x + sinOffset,
224             y: coords.bl.corner.br.y - cosOffset
225         };
226         
227         coords.br.corner = {
228             tr: {
229                 x: coords.br.x + sinOffset,
230                 y: coords.br.y - cosOffset
231             },
232             bl: {
233                 x: coords.br.x - cosOffset,
234                 y: coords.br.y - sinOffset
235             },
236             br: {
237                 x: coords.br.x,
238                 y: coords.br.y
239             }
240         };
241         coords.br.corner.tl = {
242             x: coords.br.corner.bl.x + sinOffset,
243             y: coords.br.corner.bl.y - cosOffset
244         };
245     };
246 }());
247     return Canvas;
248 });

puzzle.html

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 5 <title>Insert title here</title>
 6 <link type="text/css" href="html5_puzzle.css" rel="stylesheet" />
 7 <script type="text/javascript" src="../multi_upload/seed.js"></script>
 8 <script type="text/javascript" src='html5_puzzle.js'></script>
 9 </head>
10 <body>
11     <div id='html5_puzzle'>
12         <div id='puzzle_left'>
13             <div class='puzzle_column'>
14                 <ul>
15                     <li><img src='small_img/1.jpg' data-index='1' /></li>
16                     <li><img src='small_img/2.jpg' data-index='2' /></li>
17                     <li><img src='small_img/3.jpg' data-index='3' /></li>
18                     <li><img src='small_img/4.jpg' data-index='4' /></li>
19                     <li><img src='small_img/5.jpg' data-index='5' /></li>
20                 </ul>
21             </div>
22             <div class='puzzle_column'>
23                 <ul>
24                     <li><img src='small_img/6.jpg' data-index='6' /></li>
25                     <li><img src='small_img/7.jpg' data-index='7' /></li>
26                     <li><img src='small_img/8.jpg' data-index='8' /></li>
27                     <li><img src='small_img/9.jpg' data-index='9' /></li>
28                     <li><img src='small_img/10.jpg' data-index='10' /></li>
29                 </ul>
30             </div>
31         </div>
32         <div id='puzzle_right'>
33             <div id='puzzle_canvas'>
34                 <canvas id="canvid1"></canvas>
35                 <div id='canvas_menu'>
36                     <a href='javascript:void(0)' id='photo_delete'>删除</a> <a
37                         href='javascript:void(0)' id='photo_update'>更改图片</a>
38                 </div>
39             </div>
40             <img id="bg" src="big_img/1.jpg" width='600' height='450' />
41         </div>
42         <div id='puzzle_bottom'>
43             <a href='javascript:void(0)' id='add_img'>添加图片<input
44                 type="file" multiple="" id='fileImage'> </a> <a
45                 href='javascript:void(0)' id='upload_btn'>上传</a> <a>点击图片可以旋转,拖拽,
46                 缩放哦!</a>
47         </div>
48     </div>
49     <input type="file" id='test'>
50     <canvas id='test_canvas'></canvas>
51 </body>
52 </html>

html5_puzzle.css

 1 @CHARSET "UTF-8";
 2 
 3 #html5_puzzle {
 4     font-size: 0;
 5 }
 6 
 7 canvas {
 8     background-color: transparent;
 9     left: 0;
10     position: absolute;
11     top: 0;
12 }
13 
14 .puzzle_column,#puzzle_left,#puzzle_right,#add_img {
15     display: inline-block;
16 }
17 
18 .puzzle_column li {
19     display: block;
20     margin: 5px;
21     border: 1px solid #ffffff;
22 }
23 
24 .puzzle_column li:hover {
25     border: 1px solid #3B5998;
26     cursor: pointer;
27 }
28 
29 .puzzle_column {
30     font-size: 0;
31 }
32 
33 #puzzle_left,#puzzle_right {
34     border: 1px solid #3B5998;
35 }
36 
37 #puzzle_right,#puzzle_bottom a {
38     font-size: 14px;
39     margin: 10px 0 0 10px;
40 }
41 
42 #puzzle_bottom {
43     margin: 5px 0;
44 }
45 
46 #puzzle_canvas img {
47     
48 }
49 
50 #puzzle_canvas {
51     overflow: hidden;
52     width: 600px;
53     height: 450px;
54     position: relative;
55 }
56 
57 #add_img input {
58     position: absolute;
59     font-size: 100px;
60     right: 0;
61     top: 0;
62     opacity: 0;
63 }
64 
65 #add_img {
66     position: relative;
67     display: inline-block;
68     background: #3B5998;
69     border-radius: 4px;
70     padding: 4px 12px;
71     overflow: hidden;
72     color: #ffffff;
73 }
74 
75 #bg,#show_list {
76     display: none;
77 }
78 
79 #canvas_menu {
80     border: 1px solid red;
81     position: absolute;
82     z-index: 5;
83     top: 0;
84     left: 0;
85     display: none;
86 }
87 
88 #canvas_menu a {
89     display: inline-block;
90 }
91 
92 #test_canvas {
93     top: 700px;
94 }

html5_puzzle.js

  1 require([ 'img_upload', '../puzzle/canvasImg', '../puzzle/canvasElement' ], function(
  2         S, canvasImg, canvasElement) {
  3     var img=[];
  4     var canvas = new canvasElement.Element();
  5     canvas.init('canvid1', {
  6         width : 600,
  7         height : 450
  8     });
  9     S('.puzzle_column img').on('click',function(e){
 10         var index=this.getAttribute('data-index');
 11         $('bg').onload = function() {
 12             var ctx=$('canvid1-canvas-background').getContext('2d');
 13             ctx.clearRect(0, 0,600,450);
 14             img[0]=new canvasImg.Img($('bg'), {});
 15             canvas.setCanvasBackground(img[0]);
 16         };
 17         $('bg').setAttribute('src','medium_img/'+index+'.jpg');
 18         e.stopPropagation();
 19     });
 20     var CanvasDemo = function() {
 21         return {
 22             init : function() {
 23                 var img_list=dom.query('#puzzle_canvas img');
 24                 img[0]=new canvasImg.Img($('bg'), {});
 25                 S.each(img_list,function(i,el){
 26                         el.setAttribute('data-index',i);
 27                         img.push(new canvasImg.Img(el, {}));
 28                         canvas.addImage(img[i+1]);
 29                 });
 30                 canvas.setCanvasBackground(img[0]);
 31                 this.cornersvisible = (this.cornersvisible) ? false : true;
 32                 this.modifyImages(function(image) {
 33                     image.setCornersVisibility(this.cornersvisible);
 34                 });
 35             },
 36             modifyImages : function(fn) {
 37                 for ( var i =0, l = canvas._aImages.length; i < l; i += 1) {
 38                     fn.call(this, canvas._aImages[i]);
 39                 }
 40                 canvas.renderAll(false,false);
 41                 S('#puzzle_canvas img').remove();
 42                 img = [];
 43             }
 44         };
 45     }();
 46     function getCurImg(){
 47         var oImg=canvas._prevTransform.target;
 48         for(var i=0;i<canvas._aImages.length;i++){
 49         if(canvas._aImages[i]._oElement.src==oImg._oElement.src){
 50             return i;
 51         }
 52         }
 53     }
 54     S('#photo_delete').on('click',function(e){
 55         var i=getCurImg();
 56         canvas._aImages.splice(i,1);
 57         canvas.renderAll(true,true);
 58         $('canvas_menu').style.display="none";
 59     });
 60     S('#photo_update').on('click',function(e){
 61         $('test').click();
 62     });
 63     S('#test').on('change',function(e){
 64         var files = e.target.files || e.dataTransfer.files;
 65         var reader = new FileReader();
 66         reader.onload = (function() {
 67             return function(e) {
 68         var dataURL = e.target.result, canvas1 = document.querySelector('#test_canvas'), ctx = canvas1.getContext('2d'), img = new Image();
 69         img.onload = function(e) {
 70             if(img.width>200||img.height>200){
 71                 var prop=Math.min(200/img.width,200/img.height);
 72                 img.width=img.width*prop;
 73                 img.height=img.height*prop;
 74             }
 75             canvas1.width=img.width;
 76             canvas1.height=img.height;
 77             ctx.drawImage(img, 0, 0, img.width, img.height);
 78             S('#canvid1').html(S('#canvid1').html()+"<img src='"+canvas1.toDataURL("image/jpeg")+"'/>");
 79             var t = window.setTimeout(function() {
 80                 var i=getCurImg(),target=canvas._prevTransform.target;
 81                 console.log(target);
 82                 canvas._aImages[i]=new canvasImg.Img(dom.query('#canvid1 img')[0], {
 83                     top:target.top,
 84                     left:target.left,
 85                     scalex:target.scalex,
 86                     scaley:target.scaley,
 87                     angle:canvas.curAngle
 88                 });
 89                 canvas.renderTop();
 90                 clearTimeout(t);
 91                 S('#canvid1 img').remove();
 92             },1000);
 93         };
 94         img.src = dataURL;
 95             };
 96         })();
 97         reader.readAsDataURL(files[0]);
 98     });
 99     S('#upload_btn').on('click',function(){
100         var imgData = canvas.canvasTo('jpeg');
101         var imgValue = imgData.substr(22);
102         S.ajax({
103             url : 'http://localhost/html5/upload1.php',
104             type : 'POST',
105             data : {
106                 imgData : imgValue,
107                 file_name :'mix_img.jpeg'
108             },
109             dataType : 'text',
110             success : function(data) {
111                 alert("s");
112             }
113         });
114     });
115 });

至于用html5 input读取图片,这很简单就不贴出来了

您好,教您一个html5 canvas的问题: 我在canvas中画了多个图形,有图像(image)、直线

canvas可以实现
首先canvas要响应鼠标事件(onmousedown之类)
之后所有的图形必须要创建相应的对象,来记录他们所在的位置以及大小还有zOrder(层叠位置,在2个对象重叠的时候决定谁在上面),相应的对象放到一个数组里并按zOrder排序
当canvas的鼠标click事件触发后,按照zOrder的顺序来检测鼠标坐标在不在某个对象的区域里,如果在,则执行相应的函数
 

html5 canvas 怎让矩形倾斜 如图

html:
<canvas id=”c” width=”400px” height=”400px”>not
support</canvas>CSS:
#c{ background-color:rgba(134, 179, 225, 1);}JS:
window.onload = init;var ctx = null;var recX = 150, recY = 150, angle =
-35;function init() { var cvs = document.getElementById(‘c’); ctx =
cvs.getContext(‘2d’); drawRectangle(); drawCircle(-100, 0, 50, ‘#fff’);
drawCircle(100, 0, 50, ‘rgba(134, 179, 225, 1)’);}function setPos() {
ctx.translate(recX, recY); ctx.rotate(angle * Math.PI / 180);}function
drawRectangle() { ctx.save(); setPos(); ctx.fillStyle = ‘#fff’;
ctx.fillRect(-100, -50, 200, 100); ctx.restore();}function drawCircle(x,
y, r, fillStyle) { ctx.save(); ctx.beginPath(); setPos(); ctx.fillStyle
= fillStyle; ctx.arc(x, y, r, 0, Math.PI * 2, true); ctx.closePath();
ctx.fill(); ctx.restore();}
 

效果:
canvasElement.js 1 define(‘canvasElement’, [ ‘../multi_upload/core’
], function (S) { 2 var Canvas = window.Canvas || {}; 3…

相关文章