`

jcrop简单实例

阅读更多
1. 首先从官方网站上下载jcrop压缩包, 解压缩将js和css文件放入项目路径

http://deepliquid.com/content/Jcrop_Download.html


2. 代码实例:
<!DOCTYPE html>
<html>
<head>
<title>jcrop.html</title>
 

<link rel="stylesheet" href="jcrop/jquery.Jcrop.css" type="text/css" />

<script type="text/javascript"
	src="C:\Users\Administrator\Desktop\jquery-1.9.0.js"></script>
<script type="text/javascript" src="jcrop/jquery.Jcrop.js"></script>


<script type="text/javascript">
	$(function() {
	
		var jcrop_api,boundx,boundy,
		
		$preview=$("#preview-pane");
		$pcnt=$("#preview-pane .preview-container"),
		$pimg=$("#preview-pane .preview-container img"),
		xsize=$pcnt.width(),
		ysize=$pcnt.height();
	
		$("#target").Jcrop({
			onChange : updatePreview,
			onSelect : updatePreview,
			aspectRatio : xsize / ysize  //aspectRatio表示纵横比,这里设置为图片容器节点的宽度和高度之比
		}, function() {
			var bounds=this.getBounds();
			boundx=bounds[0];
			boundy=bounds[1];
			jcrop_api = this;
				
			$("#preview-container").appendTo(jcrop_api.ui.holder);
		});

		function updatePreview(c) {
			if (parseInt(c.w) > 0) {
				var rx = xsize / c.w;
				var ry = ysize / c.h;

				$pimg.css({
					width : Math.round(rx * boundx) + 'px',
					height : Math.round(ry * boundy) + 'px',
					marginLeft : '-' + Math.round(rx * c.x) + 'px',
					marginTop : '-' + Math.round(ry * c.y) + 'px'
				});
			}
		}

	});
</script>

</head>

<body>
	<div id="select">

		<img id="target" src="jcrop/1.jpg" />
		
		
	</div>
		
		<div id="preview-pane">
		
		<!-- $pcnt, 这里style的宽和高将会被设置为截取的固定比例 -->
		<div class="preview-container" 
			style="width:490px;height:420px;overflow:hidden">
			<img src="jcrop/1.jpg" class="jcrop-preview" alt="Preview" />
		</div>
		</div>


</body>
</html>




3. 通过jquery自定义插件对其进行简单的封装

(function($){
	$.fn.myJcrop=function(opts){
		
		console.log($(this));
		
		var jcrop_api,boundx,boundy,
		
		$preview=$("#preview-pane"),
		$pcnt=$("#preview-pane .preview-container"),
		$pimg=$("#preview-pane .preview-container img"),
		xsize=$pcnt.width(),
		ysize=$pcnt.height();
		
		
		var setting=$.extend({
			
			onChange:updatePreview,
			onSelect:updatePreview,
			aspectRatio:xsize/ysize,
		},opts||{});
		

		$(this).Jcrop(setting,function(){
			var bounds=this.getBounds();
			boundx=bounds[0];
			boundy=bounds[1];
			jcrop_api = this;
			$("#preview-container").appendTo(jcrop_api.ui.holder);
		});
		
		
		function updatePreview(c) {
			if (parseInt(c.w) > 0) {
				var rx = xsize / c.w;
				var ry = ysize / c.h;
                              //让<img>节点发生改变,也就是预览图#preview节点
				$pimg.css({
					width : Math.round(rx * boundx) + 'px',
					height : Math.round(ry * boundy) + 'px',
					marginLeft : '-' + Math.round(rx * c.x) + 'px',
					marginTop : '-' + Math.round(ry * c.y) + 'px'
				});
			}
		}

	};
	

	
	
	
})(jQuery);



通过 $("#target").myJcrop({setSelect:[0,0,490,120]}); 即可完成调用
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics