在线图片上传、预览、裁切、放大、缩小之 cropbox.js 的应用

分手后的思念是犯贱 2022-06-05 04:53 394阅读 0赞

在线图片上传、预览、裁切、放大、缩小之 cropbox.js 的应用:cropbox.js 是一个实现了图像在线剪裁的 jQuery 、YUI 插件和 JavaScript 库

上传的图片可以使用滚轮放大与缩小当前选择的图片,也可以点击按钮“+”、“”-“实现放大缩小,”后点击“裁切”后显示裁减的图片

一:效果图如下:

1、页面初始化效果图:

Center

2、点击”上传图像“之后显示的效果图,可以用滚轮实现放大与缩小,或者是点击“”+“”、“”-“”实现缩放功能:
Center 1

3、点击“裁减“按钮显示的效果图:
Center 2

二:html如下

  1. <!DOCTYPE html>
  2. <html>
  3. <head lang="en">
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
  6. <title>明信片</title>
  7. <link rel="stylesheet" href="commonUtil.css">
  8. <link rel="stylesheet" href="cropbox.css"/>
  9. <!-- <script src="http://cdn.bootcss.com/jquery/1.11.0/jquery.min.js" type="text/javascript"></script> -->
  10. <script type="text/javascript" src='jquery-1.11.1.min.js'></script>
  11. <script src="cropbox.js"></script>
  12. <script type="text/javascript" src='postcard.js'></script>
  13. </head>
  14. <body>
  15. <p class='p_txt'>上传霸屏图片:</p>
  16. <form class="container" enctype="multipart/form-data" method="post" id=''>
  17. <!-- 裁减框 -->
  18. <div class="imageBox" id="imageBox">
  19. <div class="thumbBox"></div>
  20. <div class="spinner">+</div>
  21. </div>
  22. <!-- 裁减之后的图片 -->
  23. <div class="cropped" id="cropped">
  24. <input type="image" id="cropImg" alt='裁减之后的图片' name="裁减之后的图片"/>
  25. </div>
  26. <!-- 上传、放大、缩小、裁减 -->
  27. <div class="action">
  28. <a class="selectFileDiv uploadImg">
  29. 上传图像
  30. <input type="file" id="image" name="图像">
  31. </a>
  32. <input type="button" id="btnCrop" value="裁减" name='裁减' class="selectFileDiv actionBtn"/>
  33. <input type="button" id="btnZoomIn" value="+" name='放大' class="selectFileDiv actionBtn"/>
  34. <input type="button" id="btnZoomOut" value="-" name="缩小" class="selectFileDiv actionBtn"/>
  35. </div>
  36. <p class="p_txt p_txt2">霸屏时间:</p>
  37. <div class="action paScreenTimeContainer">
  38. <div class="perTimeParent">
  39. <img src="checkIcon.png" id="checkIcon1" class="checkIcon">
  40. <input type="button" name="paScreentime1" id="1" value="8 s" class="selectFileDiv paScreentime">
  41. </div>
  42. <div class="perTimeParent">
  43. <img src="checkIcon.png" id="checkIcon2" class="checkIcon">
  44. <input type="button" name="paScreentime2" id="2" value="18 s" class="selectFileDiv paScreentime">
  45. </div>
  46. <div class="perTimeParent">
  47. <img src="checkIcon.png" id="checkIcon3" class="checkIcon">
  48. <input type="button" name="paScreentime3" id="3" value="58 s" class="selectFileDiv paScreentime">
  49. </div>
  50. </div>
  51. <p class="p_txt" id="feeContainer">您需支付:<strong id="totalFee"></strong></p>
  52. <input type="button" name="payBtn" id="payBtn" class="selectFileDiv payBtn" value="支付">
  53. </form>
  54. </body>
  55. </html>

三:css如下

  1. body{
  2. background-color: #f5f5f5;
  3. margin: 0px;
  4. padding: 0px;
  5. font-size: 2vh;
  6. }
  7. .p_txt{
  8. font-family: 微软雅黑;
  9. font-size:2vh;
  10. color:#7bbbda;
  11. letter-spacing: 4px;
  12. margin-left: 2.5vh;
  13. margin-top: 3vh;
  14. font-weight: 700;
  15. }
  16. .p_txt2{
  17. margin-top: 5vh;
  18. }
  19. .container
  20. {
  21. width:100%;
  22. height: 320px;
  23. }
  24. .imageBox
  25. {
  26. position: relative;
  27. height: 320px;
  28. width: 100%;
  29. overflow: hidden;
  30. background-repeat: no-repeat;
  31. cursor:move;
  32. }
  33. .imageBox .thumbBox
  34. {
  35. position: absolute;
  36. top: 50%;
  37. left: 50%;
  38. width: 200px;
  39. height: 200px;
  40. margin-top: -100px;
  41. margin-left: -100px;
  42. box-sizing: border-box;
  43. border: 1px solid rgb(102, 102, 102);
  44. box-shadow: 0 0 0 1000px rgba(0, 0, 0, 0.5);
  45. background: none repeat scroll 0% 0% transparent;
  46. }
  47. .imageBox .spinner
  48. {
  49. position: absolute;
  50. top: 0;
  51. left: 0;
  52. bottom: 0;
  53. right: 0;
  54. text-align: center;
  55. line-height: 320px;
  56. font-size: 8vh;
  57. color: #888585;
  58. display: none;
  59. }
  60. .cropped{
  61. height: 320px;
  62. width: 100%;
  63. background-color: #fff;
  64. text-align: center;
  65. margin: 0 auto;
  66. display: none;
  67. }
  68. #cropImg{
  69. margin-top: 60px;
  70. }
  71. .action
  72. {
  73. width:100%;
  74. margin-top: 2vh;
  75. padding-left: 1vh;
  76. height: 6vh;
  77. }
  78. .selectFileDiv{
  79. height: 6vh;
  80. line-height: 6vh;
  81. text-align: center;
  82. letter-spacing: 1px;
  83. background: #27a027;
  84. color: #fff;
  85. border-radius: 5px;
  86. font-size: 2vh;
  87. }
  88. .uploadImg {
  89. position: relative;
  90. display: inline-block;
  91. overflow: hidden;
  92. text-decoration: none;
  93. width: 13vh;
  94. }
  95. .uploadImg input {
  96. position: absolute;
  97. right: 0;
  98. top: 0;
  99. opacity: 0;
  100. }
  101. .actionBtn{
  102. float: right;
  103. width: 10vh;
  104. padding: 0px;
  105. border-width: 0px;
  106. margin-right: 2vh;
  107. }
  108. .paScreenTimeContainer{
  109. padding-left:2vw;
  110. }
  111. .perTimeParent{
  112. position:relative;
  113. width:30vw;
  114. display: inline-block;
  115. margin-right: 2vw;
  116. }
  117. .paScreentime{
  118. width: 30vw;
  119. padding: 0px;
  120. border-width: 0px;
  121. background: #dedede;
  122. }
  123. .checkIcon{
  124. position: absolute;
  125. width:3vw;
  126. right:0.5vw;
  127. top:0.5vw;
  128. display: none;
  129. z-index: 2;
  130. }
  131. .selectTimeCss{
  132. background: #fff;
  133. color: #27a027;
  134. border: 1px solid #27a027;
  135. }
  136. #feeContainer{
  137. height: 4vh;
  138. margin-top: 4vh;
  139. margin-bottom: -1vh;
  140. display: none;
  141. }
  142. .payBtn{
  143. width: 14vh;
  144. padding: 0px;
  145. border-width: 0px;
  146. display: block;
  147. margin: 5vh auto;
  148. letter-spacing: 1.6vh;
  149. font-size: 2.2vh;
  150. }

四:js如下

  1. $(function(){
  2. // 定义全局变量
  3. var globalVar = {
  4. viewFlag:0 , //0-显示裁减框,1-显示裁减之后的图片
  5. timeBtnArr:[$('#1'),$('#2'),$('#3')]
  6. };
  7. // 生成裁减对象的属性设置 var options ={ thumbBox: '.thumbBox', //显示裁减的框内容 spinner: '.spinner', //裁减框要是没有图片,则显示 // imgSrc: 'style1.png' }; // 生成裁减对象 var cropper = $('.imageBox').cropbox(options);
  8. // 上传图像
  9. $('#image').on('change', function(){
  10. var reader = new FileReader();
  11. globalVar.viewFlag = 0;
  12. refreshImgView();
  13. reader.onload = function(e) {
  14. options.imgSrc = e.target.result;
  15. cropper = $('#imageBox').cropbox(options);
  16. }
  17. reader.readAsDataURL(this.files[0]);
  18. });
  19. // 点击裁减按钮,生成裁减之后的图片,并显示裁减之后的图片
  20. $('#btnCrop').on('click', function(){
  21. // 裁减生成图片的url
  22. var imgSrc = cropper.getDataURL();
  23. $('#cropImg').attr('src',imgSrc);
  24. globalVar.viewFlag = 1;
  25. refreshImgView();
  26. });
  27. // 裁减框和裁减之后图片的显示于隐藏
  28. function refreshImgView(){
  29. if( globalVar.viewFlag == 0 ){
  30. // 显示裁剪框
  31. $('#imageBox').show();
  32. $('#cropped').hide();
  33. }else{
  34. // 显示裁减之后的图片
  35. $('#imageBox').hide();
  36. $('#cropped').show();
  37. }
  38. }
  39. // 点击缩小按钮
  40. $('#btnZoomIn').on('click', function(){
  41. cropper.zoomIn();
  42. });
  43. // 点击放大按钮
  44. $('#btnZoomOut').on('click', function(){
  45. cropper.zoomOut();
  46. });
  47. $('#1').click(function(){
  48. if( $(this).hasClass('selectTimeCss') ){
  49. }else{
  50. refreshTimeBtnView($('#1'));
  51. }
  52. });
  53. // 点击paScreentime2
  54. $('#2').click(function(){
  55. if( $(this).hasClass('selectTimeCss') ){
  56. }else{
  57. refreshTimeBtnView($('#2'));
  58. }
  59. });
  60. // 点击paScreentime2
  61. $('#3').click(function(){
  62. if( $(this).hasClass('selectTimeCss') ){
  63. }else{
  64. refreshTimeBtnView($('#3'));
  65. }
  66. });
  67. // 给选中的时间添加样式,未选中的是默认样式
  68. function refreshTimeBtnView(obj){
  69. var id = obj.attr('id');
  70. var arr = globalVar.timeBtnArr;
  71. var len = arr.length;
  72. for(var i = 0;i<len; i++){
  73. var oldId = '';
  74. if( arr[i].hasClass('selectTimeCss') ){
  75. oldId = arr[i].attr('id');
  76. arr[i].removeClass('selectTimeCss');
  77. $('#checkIcon'+ oldId).css('display','none');
  78. }
  79. }
  80. obj.addClass('selectTimeCss');
  81. $('#checkIcon'+id).css('display','block');
  82. }
  83. });

这里用的是Jquery来使用cropbox。在使用cropbox.js插件时,先引入jquery插件:

  1. <script src="http://cdn.bootcss.com/jquery/1.11.0/jquery.min.js" type="text/javascript"></script>
  2. <script src="cropbox.js"></script>

cropbox-min.js的压缩源代码如下:

  1. "use strict";!function(t){"function"==typeof define&&define.amd?define(["jquery"],t):t(jQuery)}(function(t){var e=function(e,n){var n=n||t(e.imageBox),i={state:{},ratio:1,options:e,imageBox:n,thumbBox:n.find(e.thumbBox),spinner:n.find(e.spinner),image:new Image,getDataURL:function(){var t=this.thumbBox.width(),e=this.thumbBox.height(),i=document.createElement("canvas"),a=n.css("background-position").split(" "),o=n.css("background-size").split(" "),s=parseInt(a[0])-n.width()/2+t/2,r=parseInt(a[1])-n.height()/2+e/2,u=parseInt(o[0]),g=parseInt(o[1]),c=parseInt(this.image.height),m=parseInt(this.image.width);i.width=t,i.height=e;var p=i.getContext("2d");p.drawImage(this.image,0,0,m,c,s,r,u,g);var d=i.toDataURL("image/png");return d},getBlob:function(){for(var t=this.getDataURL(),e=t.replace("data:image/png;base64,",""),n=atob(e),i=[],a=0;a<n.length;a++)i.push(n.charCodeAt(a));return new Blob([new Uint8Array(i)],{type:"image/png"})},zoomIn:function(){this.ratio*=1.1,a()},zoomOut:function(){this.ratio*=.9,a()}},a=function(){var t=parseInt(i.image.width)*i.ratio,e=parseInt(i.image.height)*i.ratio,a=(n.width()-t)/2,o=(n.height()-e)/2;n.css({"background-image":"url("+i.image.src+")","background-size":t+"px "+e+"px","background-position":a+"px "+o+"px","background-repeat":"no-repeat"})},o=function(t){t.stopImmediatePropagation(),i.state.dragable=!0,i.state.mouseX=t.clientX,i.state.mouseY=t.clientY},s=function(t){if(t.stopImmediatePropagation(),i.state.dragable){var e=t.clientX-i.state.mouseX,a=t.clientY-i.state.mouseY,o=n.css("background-position").split(" "),s=e+parseInt(o[0]),r=a+parseInt(o[1]);n.css("background-position",s+"px "+r+"px"),i.state.mouseX=t.clientX,i.state.mouseY=t.clientY}},r=function(t){t.stopImmediatePropagation(),i.state.dragable=!1},u=function(t){i.ratio*=t.originalEvent.wheelDelta>0||t.originalEvent.detail<0?1.1:.9,a()};return i.spinner.show(),i.image.οnlοad=function(){i.spinner.hide(),a(),n.bind("mousedown",o),n.bind("mousemove",s),t(window).bind("mouseup",r),n.bind("mousewheel DOMMouseScroll",u)},i.image.src=e.imgSrc,n.on("remove",function(){t(window).unbind("mouseup",r)}),i};jQuery.fn.cropbox=function(t){return new e(t,this)}});

cropbox.js源代码如下:

  1. /**
  2. * Created by ezgoing on 14/9/2014.
  3. */
  4. "use strict";
  5. (function (factory) {
  6. if (typeof define === 'function' && define.amd) {
  7. define(['jquery'], factory);
  8. } else {
  9. factory(jQuery);
  10. }
  11. }(function ($) {
  12. var cropbox = function(options, el){
  13. var el = el || $(options.imageBox),
  14. obj =
  15. {
  16. state : {},
  17. ratio : 1,
  18. options : options,
  19. imageBox : el,
  20. thumbBox : el.find(options.thumbBox),
  21. spinner : el.find(options.spinner),
  22. image : new Image(),
  23. getDataURL: function ()
  24. {
  25. var width = this.thumbBox.width(),
  26. height = this.thumbBox.height(),
  27. canvas = document.createElement("canvas"),
  28. dim = el.css('background-position').split(' '),
  29. size = el.css('background-size').split(' '),
  30. dx = parseInt(dim[0]) - el.width()/2 + width/2,
  31. dy = parseInt(dim[1]) - el.height()/2 + height/2,
  32. dw = parseInt(size[0]),
  33. dh = parseInt(size[1]),
  34. sh = parseInt(this.image.height),
  35. sw = parseInt(this.image.width);
  36. canvas.width = width;
  37. canvas.height = height;
  38. var context = canvas.getContext("2d");
  39. context.drawImage(this.image, 0, 0, sw, sh, dx, dy, dw, dh);
  40. var imageData = canvas.toDataURL('image/png');
  41. return imageData;
  42. },
  43. getBlob: function()
  44. {
  45. var imageData = this.getDataURL();
  46. var b64 = imageData.replace('data:image/png;base64,','');
  47. var binary = atob(b64);
  48. var array = [];
  49. for (var i = 0; i < binary.length; i++) {
  50. array.push(binary.charCodeAt(i));
  51. }
  52. return new Blob([new Uint8Array(array)], {type: 'image/png'});
  53. },
  54. zoomIn: function ()
  55. {
  56. this.ratio*=1.1;
  57. setBackground();
  58. },
  59. zoomOut: function ()
  60. {
  61. this.ratio*=0.9;
  62. setBackground();
  63. }
  64. },
  65. setBackground = function()
  66. {
  67. var w = parseInt(obj.image.width)*obj.ratio;
  68. var h = parseInt(obj.image.height)*obj.ratio;
  69. var pw = (el.width() - w) / 2;
  70. var ph = (el.height() - h) / 2;
  71. el.css({
  72. 'background-image': 'url(' + obj.image.src + ')',
  73. 'background-size': w +'px ' + h + 'px',
  74. 'background-position': pw + 'px ' + ph + 'px',
  75. 'background-repeat': 'no-repeat'});
  76. },
  77. imgMouseDown = function(e)
  78. {
  79. e.stopImmediatePropagation();
  80. obj.state.dragable = true;
  81. obj.state.mouseX = e.clientX;
  82. obj.state.mouseY = e.clientY;
  83. },
  84. imgMouseMove = function(e)
  85. {
  86. e.stopImmediatePropagation();
  87. if (obj.state.dragable)
  88. {
  89. var x = e.clientX - obj.state.mouseX;
  90. var y = e.clientY - obj.state.mouseY;
  91. var bg = el.css('background-position').split(' ');
  92. var bgX = x + parseInt(bg[0]);
  93. var bgY = y + parseInt(bg[1]);
  94. el.css('background-position', bgX +'px ' + bgY + 'px');
  95. obj.state.mouseX = e.clientX;
  96. obj.state.mouseY = e.clientY;
  97. }
  98. },
  99. imgMouseUp = function(e)
  100. {
  101. e.stopImmediatePropagation();
  102. obj.state.dragable = false;
  103. },
  104. zoomImage = function(e)
  105. {
  106. e.originalEvent.wheelDelta > 0 || e.originalEvent.detail < 0 ? obj.ratio*=1.1 : obj.ratio*=0.9;
  107. setBackground();
  108. }
  109. obj.spinner.show();
  110. obj.image.onload = function() {
  111. obj.spinner.hide();
  112. setBackground();
  113. el.bind('mousedown', imgMouseDown);
  114. el.bind('mousemove', imgMouseMove);
  115. $(window).bind('mouseup', imgMouseUp);
  116. el.bind('mousewheel DOMMouseScroll', zoomImage);
  117. };
  118. obj.image.src = options.imgSrc;
  119. el.on('remove', function(){$(window).unbind('mouseup', imgMouseUp)});
  120. return obj;
  121. };
  122. jQuery.fn.cropbox = function(options){
  123. return new cropbox(options, this);
  124. };
  125. }));

发表评论

表情:
评论列表 (有 0 条评论,394人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Ext图片 .

    在进行图片上传时,通常需要进行预览。而这种预览的行为通常是预览客户端的本地资源。下面就讲一下在Ext中是如何实现图片上传预览的。 首先,创建为预览图片创建一个控件: xty

    相关 图片

    > 小编推荐:[Fundebug][]提供JS错误监控、微信小程序错误监控、微信小游戏错误监控,Node.j错误监控和Java错误监控。真的是一个很好用的错误监控费服务,众多大

    相关 一个图片

    一、一个按钮上传文件操作 前台选择文件,只能通过input的file类型的文件选择框操作。但有时却为了界面的美观,要求用按钮来完成。 第一步、隐藏文件选择框 第二步、