html2canvas使用方法,js截图,压缩,上传

npm install html2canvas
import html2canvas from 'html2canvas';

1.插件截图生成canvas,转成blob,再转成file文件流

html2canvas($("#app")[0]).then(function(canvas) {
  canvas.toBlob((blobObj)=>{
    let file = new window.File([blobObj], 'capture.jpg', {type: 'image/jpeg'});
    let formData = new FormData();
    formData.append("file",file);
    $.ajax({
      type: 'post',
      url: 'xxxxx',
      data: formData,
      contentType:false,
      processData:false,
      success: function (data) {
        console.info(data);
      },
      error: function (data) {
        console.info(data);
      }
    });
  });
});

2.插件截图生成canvas,先转成base64压缩,再转成blob,再转成file文件流

html2canvas($("#app")[0]).then(function(canvas) {
  var dataURL =canvas.toDataURL('image/jpeg',0.5);  //0.5是图片质量
  var arr = dataURL.split(','),
  mime = arr[0].match(/:(.*?);/)[1],
  bstr = atob(arr[1]),
  n = bstr.length,
  u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  let blob=new Blob([u8arr], { type: mime });
  let file = new window.File([blob], 'thumbnail.jpg', {type: 'image/jpeg'});
  let formData = new FormData();
  formData.append("file",file);
  $.ajax({
    type: 'post',
    url: 'xxxx',
    data: formData,
    contentType:false,
    processData:false,
    success: function (data) {
      console.info(data);
    },
    error: function (data) {
      console.info(data);
    }
  });
});

3.封装成函数,调用后用.then(file=>{Todo...})接收

/**
   * @name:利用html2canvas插件把DOM节点截图成为图片
   * @param {DOM} DOM 需要截图的DOM节点 document.getElementById('box');
   * @param {string} fileName 生成截图的名称 例如:'thumbnail.jpg'
   * @param {number} ratio 图片压缩率(0.1-1)
   */
  myHtml2canvas(DOM,fileName,ratio){
    return new Promise((resolve)=>{
      html2canvas(DOM).then(function (canvas) {
        var dataURL = canvas.toDataURL('image/jpeg',ratio);
        var arr = dataURL.split(','),
          mime = arr[0].match(/:(.*?);/)[1],
          bstr = atob(arr[1]),
          n = bstr.length,
          u8arr = new Uint8Array(n);
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
        }
        let blob = new Blob([u8arr], { type: mime });
        let file = new window.File([blob], fileName, {
          type: 'image/jpeg',
        });
        resolve(file);
      });
    })
  }
  //使用
  myHtml2canvas($('#componentContainer')[0],'thumbnail.jpg',0.5).then((file)=>{
    console.log(file);
  })

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
压缩HTML: 可以使用多种工具来压缩HTML,例如HTMLMinifier或UglifyJS等。这些工具可以删除不必要的空格、注释和其他字符,从而减小文件大小。以下是使用HTMLMinifier进行HTML压缩的示例代码: ```javascript const html = '<html><head><title>Hello World</title></head><body><p>Hello, world!</p></body></html>'; const minifiedHtml = htmlMinifier.minify(html, { collapseWhitespace: true, removeComments: true, minifyCSS: true, minifyJS: true }); ``` 图片上传: 可以使用HTML5的File API来实现图片上传。以下是一个基本的示例: ```html <input type="file" id="upload-input"> <script> const input = document.getElementById('upload-input'); input.addEventListener('change', (e) => { const file = e.target.files[0]; const reader = new FileReader(); reader.onload = (event) => { const imageData = event.target.result; // 图片数据 // 将图片数据上传到服务器 }; reader.readAsDataURL(file); }); </script> ``` JS Canvas 修改图片尺寸和压缩大小: 可以使用canvas的API来修改图片的尺寸和压缩图片大小。以下是一个基本的示例: ```html <input type="file" id="upload-input"> <canvas id="canvas"></canvas> <script> const input = document.getElementById('upload-input'); const canvas = document.getElementById('canvas'); const context = canvas.getContext('2d'); input.addEventListener('change', (e) => { const file = e.target.files[0]; const reader = new FileReader(); reader.onload = (event) => { const img = new Image(); img.onload = () => { // 计算缩小后的尺寸 const maxWidth = 300; const maxHeight = 300; let width = img.width; let height = img.height; if (width > height) { if (width > maxWidth) { height *= maxWidth / width; width = maxWidth; } } else { if (height > maxHeight) { width *= maxHeight / height; height = maxHeight; } } canvas.width = width; canvas.height = height; // 绘制缩小后的图片 context.drawImage(img, 0, 0, width, height); // 压缩图片 const quality = 0.7; const imageData = canvas.toDataURL('image/jpeg', quality); // 将图片数据上传到服务器 }; img.src = event.target.result; }; reader.readAsDataURL(file); }); </script> ``` 以上是一个基本的实现,具体的实现方式可以根据需求进行修改。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值