基于jQuery功能非常强大的图片裁剪插件
今天我们要来介绍一款基于jQuery功能非常强大的图片裁剪插件,这款jQuery图片裁剪插件可以选择裁剪框的尺寸比例,可以设置高宽尺寸,同时可以设置图片翻转角度,当然也支持图片的缩放,裁剪框也可以用鼠标拖动。效果图如下:
来看看实现的代码,这里我们主要来看JavaScript代码
获取图片的Canvas画布:
function getSourceCanvas(image, data) { var canvas = $(‘<canvas>‘)[0], context = canvas.getContext(‘2d‘), width = data.naturalWidth, height = data.naturalHeight, rotate = data.rotate, rotated = getRotatedSizes({ width: width, height: height, degree: rotate }); if (rotate) { canvas.width = rotated.width; canvas.height = rotated.height; context.save(); context.translate(rotated.width / 2, rotated.height / 2); context.rotate(rotate * Math.PI / 180); context.drawImage(image, -width / 2, -height / 2, width, height); context.restore(); } else { canvas.width = width; canvas.height = height; context.drawImage(image, 0, 0, width, height); } return canvas; }
加载图片:
prototype.load = function (url) { var options = this.options, $this = this.$element, crossOrigin, bustCacheUrl, buildEvent, $clone; if (!url) { if ($this.is(‘img‘)) { if (!$this.attr(‘src‘)) { return; } url = $this.prop(‘src‘); } else if ($this.is(‘canvas‘) && SUPPORT_CANVAS) { url = $this[0].toDataURL(); } } if (!url) { return; } buildEvent = $.Event(EVENT_BUILD); $this.one(EVENT_BUILD, options.build).trigger(buildEvent); // Only trigger once if (buildEvent.isDefaultPrevented()) { return; } if (options.checkImageOrigin && isCrossOriginURL(url)) { crossOrigin = ‘anonymous‘; if (!$this.prop(‘crossOrigin‘)) { // Only when there was not a "crossOrigin" property bustCacheUrl = addTimestamp(url); // Bust cache (#148) } } this.$clone = $clone = $(‘<img>‘); $clone.one(‘load‘, $.proxy(function () { var naturalWidth = $clone.prop(‘naturalWidth‘) || $clone.width(), naturalHeight = $clone.prop(‘naturalHeight‘) || $clone.height(); this.image = { naturalWidth: naturalWidth, naturalHeight: naturalHeight, aspectRatio: naturalWidth / naturalHeight, rotate: 0 }; this.url = url; this.ready = true; this.build(); }, this)).one(‘error‘, function () { $clone.remove(); }).attr({ src: bustCacheUrl || url, crossOrigin: crossOrigin }); // Hide and insert into the document $clone.addClass(CLASS_HIDE).insertAfter($this); };
预览截图:
prototype.initPreview = function () { var url = this.url; this.$preview = $(this.options.preview); this.$viewBox.html(‘<img src="‘ + url + ‘">‘); // Override img element styles // Add `display:block` to avoid margin top issue (Occur only when margin-top <= -height) this.$preview.each(function () { var $this = $(this); $this.data(CROPPER_PREVIEW, { width: $this.width(), height: $this.height(), original: $this.html() }).html(‘<img src="‘ + url + ‘" style="display:block;width:100%;min-width:0!important;min-height:0!important;max-width:none!important;max-height:none!important;image-orientation: 0deg!important">‘); }); };
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。