How does js realize page screenshot generation and sharing function, and how to pass it to the backend

Generate and share pictures through html2canvas

What is html2canvs?

html2canvas 的作用就是允许让我们直接在用户浏览器上拍摄网页或其部分的“截图”。

Its screenshots are DOM based and therefore may not be 100% accurate to a true representation as it does not generate actual screenshots but constructs them based on information available on the page. So a more common application scenario is that we can use it to generate sharing images on the H5 side.

  1. download

html2canvas official website: http://html2canvas.hertzen.com/

  1. use
//引入改文件
<script src="./js/html2canvas.js"></script>
  1. transfer
 // 获取分享图片 base64
 function getShareImgBase64 () {
    
    
     return new Promise((resolve) => {
    
    
         setTimeout(() => {
    
    
             // #capture 就是我们要获取截图对应的 DOM 元素选择器
             html2canvas(document.querySelector('#capture'), {
    
    
                 useCORS: true, // 【重要】开启跨域配置
                 scale: window.devicePixelRatio < 3 ? window.devicePixelRatio : 2,
                 allowTaint: true, // 允许跨域图片
             }).then((canvas) => {
    
    
                 const bs64 = canvas.toDataURL('image/jpeg', 1.0);
                 resolve(bs64);
             });
         }, 300); // 这里加上 300ms 的延迟是为了让 DOM 元素完全渲染完成后再进行图片的生成
     });
 }
 //通过then接收
getShareImgBase64().then((res) => {
    
    
    console.log(res);
})

Note: The generated picture is in bs64 format, and it is recommended to use the form form to upload the file directly to the backend

let bytes = window.atob(bs64)
let ab = new ArrayBuffer(bytes.length)
let ia = new Uint8Array(ab)
for (let i = 0; i < bytes.length; i++) {
    
    
  ia[i] = bytes.charCodeAt(i)
}
let imgs = new File([ab], name, {
    
     type: 'image/jpg' })
const formData = new FormData()
formData.append('file', imgs)
//此处上传直接使用ajax还,直接把formData放到data那里就行,不需要键值对形势

If you encounter an error:
insert image description here

Error: Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded
Error: Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded

Solution: Replace the line of code that reported the error above with the following one.

let bytes = atob(bs64.replace(/^data:image\/(png|jpeg|jpg);base64,/, ''));

Complete code:

// 获取分享图片 base64
function getShareImgBase64 () {
    
    
 return new Promise((resolve) => {
    
    
     setTimeout(() => {
    
    
         // #capture 就是我们要获取截图对应的 DOM 元素选择器
         html2canvas(document.querySelector('#capture'), {
    
    
             useCORS: true, // 【重要】开启跨域配置
             scale: window.devicePixelRatio < 3 ? window.devicePixelRatio : 2,
             allowTaint: true, // 允许跨域图片
         }).then((canvas) => {
    
    
             const bs64 = canvas.toDataURL('image/jpeg', 1.0);
             let bytes = window.atob(bs64.replace(/^data:image\/(png|jpeg|jpg);base64,/, ''))
             let ab = new ArrayBuffer(bytes.length)
             let ia = new Uint8Array(ab)
             for (let i = 0; i < bytes.length; i++) {
    
    
                 ia[i] = bytes.charCodeAt(i)
             }
             let imgs = new File([ab], name, {
    
     type: 'image/jpg' })

             resolve({
    
    "bs64":bs64,"imgs":imgs});
         });
     }, 300); // 这里加上 300ms 的延迟是为了让 DOM 元素完全渲染完成后再进行图片的生成
 });
}

Screenshot effect:
insert image description here

Guess you like

Origin blog.csdn.net/qq_44749901/article/details/126179120