ImageClipboard js粘贴剪切板图片,已测试,可用,可获得base64

ImageClipboard js粘贴剪切板图片,已测试,可用,可获得base64
具体用到自己项目的时候,拿源码改成自己的库,从写一遍

3个小问题

  1. onpaste 执行了两遍,一次是图片加载完成,一次是加载图片之前。按说 应该搞两个事件来分别调用
  2. pasteCatcher 应该是作为一个保底实现,我也没看明白是怎么获取剪切板的图片,怎么就能拿到base64了,反正通过e.clipboardData.items是拿到图片了
  3. 大哥遍历了整个剪切板的图片,全部走了一遍函数,这性能会不会有点问题,也不知道。

结论

不管怎么说,这个代码能用,别的库,好多都不能用。

index.html

<!DOCTYPE html>
<html>

<head>
  <!-- https://github.com/jorgenbs/ImageClipboard/tree/master -->
  <script src="ImageClipboard.js"></script>
</head>

<body>

  <div id="box">
  </div>
<script type="text/javascript">

  var clipboard = new ImageClipboard('#box');
  
  //onpaste-callback can also be passed as second argument
  //in the constructor above.
  clipboard.onpaste = function (base64) {
    //do stuff with the pasted image
    console.info('clipboard.onpaste')
  };

  //you can also pass in single DOM-element instead of 
  //query as the first parameter.

</script>

</body>

</html>

ImageClipboard.js

/*jshint boss:true, laxcomma: true, expr: true*/
!function (name, definition) {
  if (typeof module != 'undefined') module.exports = definition;
  else if (typeof define == 'function' && define.amd) define(name, definition);
  else this[name] = definition;
}('ImageClipboard', function (selector, callback) {
  'use strict';

  var self = typeof this === 'object' ? this : {};
  self.el = null;
  self.pasteCatcher = null;
  self.clipImage = null;
  self.onpaste = null;
  self.browserSupport = true;

  self.init = function (selector, callback) {

      if (typeof selector === "string") {
          self.el = document.querySelector(selector);
      }
      else if (_isElement(selector)) self.el = selector;
      else return false;

      self.pasteCatcher = null;
      self.clipImage = null;

      self.onpaste = typeof callback === 'function' ? callback : function () { };

      //pasting not supported, make workaround
      if (!window.Clipboard) {
          self.pasteCatcher = _makePasteCatcher();
      }

      window.addEventListener('paste', self.pasteHandler);

      return self;
  };

  self.pasteHandler = function (e) {
      var items;

      if (e.clipboardData && e.clipboardData.items) {
          items = e.clipboardData.items;

          if (items) {
              items = Array.prototype.filter.call(items, function (element) {
                  return element.type.indexOf("image") >= 0;
              });
              console.info('items.length', items.length)
              Array.prototype.forEach.call(items, function (item) {
                  var blob = item.getAsFile();

                  var rdr = new FileReader();
                  rdr.onloadend = function () {
                      _loadImage(rdr.result);
                  };

                  rdr.readAsDataURL(blob);
              });
          }
      }
      else if (self.pasteCatcher) {
          //no direct access to clipboardData (firefox)
          //use the pastecatcher
          setTimeout(function () {

              var child = self.pasteCatcher.firstElementChild;

              if (child && child.tagName == "IMG") {
                  _loadImage(child.src);
              }

          }, 5);
      }
  };

  function _makePasteCatcher() {
      var pasteBox = document.createElement("div");

      pasteBox.setAttribute("id", "paste_catcher");
      pasteBox.setAttribute("contenteditable", "");
      pasteBox.style.opacity = 0;

      document.body.insertBefore(pasteBox, document.body.firstChild);

      pasteBox.focus();
      self.el.addEventListener("click", function () { pasteBox.focus(); });

      return pasteBox;
  }

  function _loadImage(source) {
      var img = new Image();
      self.el.innerHTML = "";

      img.onload = function () {
          //got picture, display it
          var imgContainer = document.createElement("img");
          imgContainer.src = img.src;
          imgContainer.style.maxHeight = "100%";
          imgContainer.style.maxHeight = "100%";
          self.el.appendChild(imgContainer);

          //empty out the ol' pastecatcher
          if (self.pasteCatcher) self.pasteCatcher.innerHTML = "";

          self.clipImage = img;

          if (typeof self.onpaste === 'function')
              self.onpaste(img.src);
      };

      img.src = source;

      self.onpaste.call(self, source.split(",")[1]); //callback(base64, file-type)
  }

  function _isElement(obj) {
      return typeof HTMLElement === "object" ? obj instanceof HTMLElement :
        obj && typeof obj === "object" && obj.nodeType === 1 && typeof obj.nodeName === "string";
  }

  return self.init(selector, callback);
});
posted @ 2024-01-11 10:45  彭成刚  阅读(118)  评论(0编辑  收藏  举报