jquery cropbox更改选项

时间:2018-06-15 11:05:35

标签: javascript jquery

这是" cropbox"的github来源。 JavaScript代码。

一切正常,但是我在页面上使用它来处理两个不同的图像,当页面加载时它调用了这个

$(window).on('load', function() {
    var options = {
        thumbBox: '.thumbBox',
        spinner: '.spinner',
        imgSrc: 'avatar.png'
    }
    var cropper;
    $('#file').on('change', function() {
        var reader = new FileReader();
        reader.onload = function(e) {
            options.imgSrc = e.target.result;
            cropper = $('.imageBox').cropbox(options);
        }
        reader.readAsDataURL(this.files[0]);
        this.files = [];
    })
    $('#btnCrop').on('click', function() {
        var img = cropper.getDataURL()
        $('.cropped').append('<img src="' + img + '">');
    })
    $('#btnZoomIn').on('click', function() {
        cropper.zoomIn();
    })
    $('#btnZoomOut').on('click', function() {
        cropper.zoomOut();
    })
});

但我似乎无法改变&#34;选项&#34;务实。我试过了

options = {
    thumbBox: '.smallThumbBox',
    spinner: '.spinner',
    imgSrc: 'avatar.png'
}

jQuery.fn.cropbox.options = {
    thumbBox: '.smallThumbBox',
    spinner: '.spinner',
    imgSrc: 'avatar.png'
}

但似乎没有任何改变选择。

谁能告诉我我做错了什么?

1 个答案:

答案 0 :(得分:0)

我更改为使用文档就绪事件处理程序并注释掉行this.files = [];,因为它产生了错误(请检查控制台日志)

&#13;
&#13;
/**
 * Created by ezgoing on 14/9/2014.
 */

"use strict";
(function(factory) {
  if (typeof define === 'function' && define.amd) {
    define(['jquery'], factory);
  } else {
    factory(jQuery);
  }
}(function($) {
  var cropbox = function(options, el) {
    var el = el || $(options.imageBox),
      obj = {
        state: {},
        ratio: 1,
        options: options,
        imageBox: el,
        thumbBox: el.find(options.thumbBox),
        spinner: el.find(options.spinner),
        image: new Image(),
        getDataURL: function() {
          var width = this.thumbBox.width(),
            height = this.thumbBox.height(),
            canvas = document.createElement("canvas"),
            dim = el.css('background-position').split(' '),
            size = el.css('background-size').split(' '),
            dx = parseInt(dim[0]) - el.width() / 2 + width / 2,
            dy = parseInt(dim[1]) - el.height() / 2 + height / 2,
            dw = parseInt(size[0]),
            dh = parseInt(size[1]),
            sh = parseInt(this.image.height),
            sw = parseInt(this.image.width);

          canvas.width = width;
          canvas.height = height;
          var context = canvas.getContext("2d");
          context.drawImage(this.image, 0, 0, sw, sh, dx, dy, dw, dh);
          var imageData = canvas.toDataURL('image/png');
          return imageData;
        },
        getBlob: function() {
          var imageData = this.getDataURL();
          var b64 = imageData.replace('data:image/png;base64,', '');
          var binary = atob(b64);
          var array = [];
          for (var i = 0; i < binary.length; i++) {
            array.push(binary.charCodeAt(i));
          }
          return new Blob([new Uint8Array(array)], {
            type: 'image/png'
          });
        },
        zoomIn: function() {
          this.ratio *= 1.1;
          setBackground();
        },
        zoomOut: function() {
          this.ratio *= 0.9;
          setBackground();
        }
      },
      setBackground = function() {
        var w = parseInt(obj.image.width) * obj.ratio;
        var h = parseInt(obj.image.height) * obj.ratio;

        var pw = (el.width() - w) / 2;
        var ph = (el.height() - h) / 2;

        el.css({
          'background-image': 'url(' + obj.image.src + ')',
          'background-size': w + 'px ' + h + 'px',
          'background-position': pw + 'px ' + ph + 'px',
          'background-repeat': 'no-repeat'
        });
      },
      imgMouseDown = function(e) {
        e.stopImmediatePropagation();

        obj.state.dragable = true;
        obj.state.mouseX = e.clientX;
        obj.state.mouseY = e.clientY;
      },
      imgMouseMove = function(e) {
        e.stopImmediatePropagation();

        if (obj.state.dragable) {
          var x = e.clientX - obj.state.mouseX;
          var y = e.clientY - obj.state.mouseY;

          var bg = el.css('background-position').split(' ');

          var bgX = x + parseInt(bg[0]);
          var bgY = y + parseInt(bg[1]);

          el.css('background-position', bgX + 'px ' + bgY + 'px');

          obj.state.mouseX = e.clientX;
          obj.state.mouseY = e.clientY;
        }
      },
      imgMouseUp = function(e) {
        e.stopImmediatePropagation();
        obj.state.dragable = false;
      },
      zoomImage = function(e) {
        e.originalEvent.wheelDelta > 0 || e.originalEvent.detail < 0 ? obj.ratio *= 1.1 : obj.ratio *= 0.9;
        setBackground();
      }

    obj.spinner.show();
    obj.image.onload = function() {
      obj.spinner.hide();
      setBackground();

      el.bind('mousedown', imgMouseDown);
      el.bind('mousemove', imgMouseMove);
      $(window).bind('mouseup', imgMouseUp);
      el.bind('mousewheel DOMMouseScroll', zoomImage);
    };
    obj.image.src = options.imgSrc;
    el.on('remove', function() {
      $(window).unbind('mouseup', imgMouseUp)
    });

    return obj;
  };

  jQuery.fn.cropbox = function(options) {
    return new cropbox(options, this);
  };
}));
$(document).ready(function() {
  var options = {
    thumbBox: '.thumbBox',
    spinner: '.spinner',
    imgSrc: 'avatar.png'
  }
  var cropper = $('.imageBox').cropbox(options);
   console.log("cropper options:",cropper.options);// now not undefined
  $( cropper.options.spinner).html( "Get Loaded...").fadeOut(2000);
  $('#file').on('change', function() {
    var reader = new FileReader();
    reader.onload = function(e) {
      options.imgSrc = e.target.result;
      cropper = $('.imageBox').cropbox(options);
    }
    reader.readAsDataURL(this.files[0]);
    console.log(cropper);
   // this.files = [];
  });
  $('#btnCrop').on('click', function() {
    var img = cropper.getDataURL()
    $('.cropped').append('<img src="' + img + '">');
  });
  $('#btnZoomIn').on('click', function() {
    cropper.zoomIn();
  });
  $('#btnZoomOut').on('click', function() {
    cropper.zoomOut();
  });
 
  
});
&#13;
.imageBox {
  position: relative;
  height: 400px;
  width: 400px;
  border: 1px solid #aaa;
  background: #fff;
  overflow: hidden;
  background-repeat: no-repeat;
  cursor: move;
}

.imageBox .thumbBox {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 200px;
  height: 200px;
  margin-top: -100px;
  margin-left: -100px;
  box-sizing: border-box;
  border: 1px solid rgb(102, 102, 102);
  box-shadow: 0 0 0 1000px rgba(0, 0, 0, 0.5);
  background: none repeat scroll 0% 0% transparent;
}

.imageBox .spinner {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  text-align: center;
  line-height: 400px;
  background: rgba(0, 0, 0, 0.7);
}

.container {
  position: absolute;
  top: 10%;
  left: 10%;
  right: 0;
  bottom: 0;
}

.action {
  width: 400px;
  height: 30px;
  margin: 10px 0;
}

.cropped>img {
  margin-right: 10px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="container">
  <div class="imageBox">
    <div class="thumbBox"></div>
    <div class="spinner" style="display: none">Loading...</div>
  </div>
  <div class="action">
    <input type="file" id="file" style="float:left; width: 250px">
    <input type="button" id="btnCrop" value="Crop" style="float: right">
    <input type="button" id="btnZoomIn" value="+" style="float: right">
    <input type="button" id="btnZoomOut" value="-" style="float: right">
  </div>
  <div class="cropped">

  </div>
</div>
&#13;
&#13;
&#13;

更新注意,我认为你的问题更多地落在实例选项的范围内,而不是像我最初想的那样改变图像。要做到这一点,你需要参考选项,请注意我如何设置&#34; cropper&#34;到那个实例,然后改变加载器的文本,然后淡出它。