|
| 1 | +(function (api, document){ |
| 2 | + var |
| 3 | + min = Math.min, |
| 4 | + |
| 5 | + support = !!(function(){ |
| 6 | + var canvas = document.createElement('Canvas'), support = canvas.getContext && ~canvas.toDataURL("image/png").indexOf("data:image/png"); |
| 7 | + canvas = null; |
| 8 | + return support; |
| 9 | + })(), |
| 10 | + |
| 11 | + notSupport = support ? false : function (img){ return img; } |
| 12 | + ; |
| 13 | + |
| 14 | + api.extend({ |
| 15 | + |
| 16 | + canvas: support, |
| 17 | + |
| 18 | + rotate: notSupport || function (img, deg){ |
| 19 | + var width = img.width, height = img.height; |
| 20 | + |
| 21 | + return Canvas(!(deg % 180) ? width : height, (deg % 180) ? width : height) |
| 22 | + .rotate(deg) |
| 23 | + .draw(img, (deg == 180 || deg == 270 ? -width : 0), (deg == 90 || deg == 180 ? -height : 0), width, height) |
| 24 | + .ok() |
| 25 | + ; |
| 26 | + }, |
| 27 | + |
| 28 | + crop: notSupport || function (img, x, y, w, h){ |
| 29 | + return Canvas(w, h).draw(img, x, y, w, h, 0, 0, w, h).ok(); |
| 30 | + }, |
| 31 | + |
| 32 | + resize: notSupport || function (img, width, height){ |
| 33 | + return Canvas(width, height).draw(img, 0, 0, width, height).ok(); |
| 34 | + }, |
| 35 | + |
| 36 | + resizeByMax: notSupport || function (img, width, height){ |
| 37 | + if( !height ) height = width; |
| 38 | + |
| 39 | + var |
| 40 | + srcW = img.width |
| 41 | + , srcH = img.height |
| 42 | + , srcF = srcW / srcH |
| 43 | + , dstF = width / height |
| 44 | + ; |
| 45 | + |
| 46 | + if( srcF >= dstF ){ |
| 47 | + width = min(srcW, width); |
| 48 | + height = width / srcF; |
| 49 | + } else { |
| 50 | + height = min(srcH, height); |
| 51 | + width = height * srcF; |
| 52 | + } |
| 53 | + |
| 54 | + return Canvas(width, height).draw(img).ok(); |
| 55 | + } |
| 56 | + |
| 57 | + }); |
| 58 | + |
| 59 | + |
| 60 | + // @private |
| 61 | + function Canvas(w, h){ |
| 62 | + if( !(this instanceof Canvas) ) return new Canvas(w, h); |
| 63 | + this.canvas = document.createElement('canvas'); |
| 64 | + this.ctx = this.canvas.getContext('2d'); |
| 65 | + this.width = this.canvas.width = w; |
| 66 | + this.height = this.canvas.height = h; |
| 67 | + } |
| 68 | + Canvas.prototype = { |
| 69 | + constructor: Canvas, |
| 70 | + |
| 71 | + draw: function (img, sx, sy, sw, sh, dx, dy, dw, dh){ |
| 72 | + var width = this.width, height = this.height; |
| 73 | + if( typeof dx !== 'undefined' ) |
| 74 | + this.ctx.drawImage(img, sx||0, sy||0, sw||width, sh||height, dx||0, dy||0, dw||width, dh||height); |
| 75 | + else |
| 76 | + this.ctx.drawImage(img, sx||0, sy||0, sw||width, sh||height); |
| 77 | + return this; |
| 78 | + }, |
| 79 | + |
| 80 | + rotate: function (deg){ |
| 81 | + this.ctx.rotate(deg * Math.PI / 180); |
| 82 | + return this; |
| 83 | + }, |
| 84 | + |
| 85 | + ok: function (){ |
| 86 | + this.ctx = null; |
| 87 | + return this.canvas; |
| 88 | + } |
| 89 | + }; |
| 90 | +})(FileAPI, document); |
0 commit comments