为了使用户能自定义个人头像,需要提供一个对上传图片的截图功能,当前很多网站特别是SNS类网站都提供这样的功能,非常实用。主要实现的形式有两种,一种是flash截图另一种就是javascript截图,两种方法各有秋千,关于Flash截图可以参考一下UcHome程序中头像上传功能,但这不是我要讨论的话题,我这里主要是如何实现javascript 截图,利用jQuery的imgAreaSelect插件,轻松实现自定义头像[avatar]javascript截图功能。

一,准备:
两个JS文件
1,jquery.js 下载:jquery.js
2,jquery.imgareaselect.js 下载:jquery.imgareaselect.js[imgareaselect-0.6.2.zip]

二,使用

  1. function preview(img, selection){
  2. var scaleX = 100 / selection.width;
  3. var scaleY = 100 / selection.height;
  4. //动态小头像 获取当前选中框的宽度,高度,左边框,右边框
  5. $('#biuuu + div > img').css({
  6. width: Math.round(scaleX * 400) + 'px',
  7. height: Math.round(scaleY * 300) + 'px',
  8. marginLeft: '-' + Math.round(scaleX * selection.x1) + 'px',
  9. marginTop: '-' + Math.round(scaleY * selection.y1) + 'px'
  10. });
  11. }
  12. //加载小头像
  13. $(document).ready(function () {
  14. $('<div><img src="biuuu.jpg" style="position: relative;" /></div>')
  15. .css({
  16. float: 'left',
  17. position: 'relative',
  18. overflow: 'hidden',
  19. width: '100px',
  20. height: '100px'
  21. })
  22. .insertAfter($('#biuuu'));
  23. });
  24. //初始化加载
  25. $(window).load(function () {
  26. $('#biuuu').imgAreaSelect({ aspectRatio: '1:1', onSelectChange: preview });
  27. });

三,调用

  1. <div class="container">
  2. <p>
  3. <img id="biuuu" src="biuuu.jpg" title="biuuu" style="float: left; margin-right: 10px;" />
  4. </p>
  5. </div>

使用上面的javascript截图进行扩展可以实现很多的动态功能,jQuery提供的imgAreaSelect插件调用非常简单,其它相关应用可参考:imgAreaSelect Examples

使用jQuery插件imgAreaSelect实现javascript截图还是非常简单的,基本上就是一个动态的图像显示,获取源图片的位置和选取框的大小[宽度和高度],轻松实现javascript截图功能。

点我下载DEMO:javascript截图 imgAreaSelect插件demo

 

原文地址:http://www.biuuu.com/p189.html

posted on 2010-09-10 13:14  Hong.S  阅读(3706)  评论(2编辑  收藏  举报