首页 > 其他分享 >ImageClipboard js粘贴剪切板图片,已测试,可用,可获得base64

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

时间:2024-01-11 10:56:42浏览次数:26  
标签:function items self base64 js typeof 剪切板 var onpaste

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);
});

标签:function,items,self,base64,js,typeof,剪切板,var,onpaste
From: https://www.cnblogs.com/pengchenggang/p/17958061

相关文章

  • mysql修改json字段sql备份
    updatedec_maina,dec_main_copy20240110bseta.ie_Date=b.ie_Date,a.declaration_data=b.declaration_data,a.custom_state=b.custom_state,a.content=JSON_SET(a.cont......
  • 推荐一个页面引导库 driver.js
    页面引导功能是web开发中常见的一个功能。通过页面引导功能,你可以让用户第一时间熟悉你的页面功能。今天给大家推荐一个页面引导库driver.js。简介driver.js是一款用原生js实现的页面引导库,上手非常简单,体积在gzip压缩下仅仅5kb。我们来看下如何使用driver.jsimport......
  • jsp有哪些内置对象
    Laravel是一个流行的PHP框架,它具有出色的可测试性,可以帮助开发人员在更短的时间内编写可靠的代码。但是,即使使用了这个框架,也可能会出现测试覆盖率较低的情况。测试覆盖率是指代码中已由测试案例覆盖的部分比例。测试覆盖率越高,代码质量越高。在本文中,我们将分享几种技巧,帮助您提......
  • js中反斜杠替换问题
    在windows机器上,vscode复制完相对路径,路径为反斜杠想在控制台用js将反斜杠替换为正斜杠,结果失败js的字符串是不能直接写单个反斜杠的letstr='src\aaa\bbb\ccc'实际上会变成'srcaaa\bbbccc'只有\b被保留,应该是当成正则原字符了,待验证而要真正还原反斜杠,需要转义letstr......
  • js 执行上下文与作用域
    执行上下文(以下简称“上下文”)的概念在JavaScript中是颇为重要的。变量或函数的上下文决定了它们可以访问哪些数据,以及它们的行为。每个上下文都有一个关联的变量对象(variableobject),而这个上下文中定义的所有变量和函数都存在于这个对象上。全局上下文是最外层的上下文。......
  • js typeof
    typeof操作符最适合用来判断一个变量是否为原始类型。更确切地说,它是判断一个变量是否为字符串、数值、布尔值或undefined的最好方式。lets="Nicholas";letb=true;leti=22;letu;letn=null;leto=newObject();console.log(typeof......
  • js 原始值
    原始值和引用值在通过变量复制时也有所不同。在通过变量把一个原始值赋值到另一个变量时,原始值会被复制到新变量的位置。请看下面的例子:letnum1=5;letnum2=num1;这里,num1包含数值5。当把num2初始化为num1时,num2也会得到数值5。这个值跟存储在num1中的5是......
  • js 函数
    函数对任何语言来说都是核心组件,因为它们可以封装语句,然后在任何地方、任何时间执行。ECMAScript中的函数使用function关键字声明,后跟一组参数,然后是函数体。以下是函数的基本语法:functionfunctionName(arg0,arg1,...,argN){statements}下面是一个例子:functionsayHi(......
  • js switch语句
    with语句的用途是将代码作用域设置为特定的对象,其语法是:with(expression)statement;使用with语句的主要场景是针对一个对象反复操作,这时候将代码作用域设置为该对象能提供便利,如下面的例子所示:letqs=location.search.substring(1);lethostName=location.hostnam......
  • js for
    for-in语句是一种严格的迭代语句,用于枚举对象中的非符号键属性,语法如下:for(propertyinexpression)statement下面是一个例子:for(constpropNameinwindow){document.write(propName);}这个例子使用for-in循环显示了BOM对象window的所有属性。每次执行循环,都会给......