zoukankan      html  css  js  c++  java
  • html2canvas--页面dom转图片

    最近工作上遇到需求,要实现分享页面功能。(具体就是把我们页面的dom转化为一张图保存,然后通过图片进行分享)

    公司内部有相对应的spt(html-to-image)外部就不适用了。

    自己也调研了一下发现常见的可引用 html2canvas.js来实现。仔细看了官网(http://html2canvas.hertzen.com),总结一下自己的用法:

     
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="./html2canvas.js"></script>
    <style>
    .box {
    500px;
    height: 500px;
    color: red;
    background-color: black;
    }
    </style>
    </head>
    <body>
    <div class="box">
    <div>佳文</div>
    <img src="https://img.alicdn.com/imgextra/i3/O1CN014iA0NU1m4hpCi1B9t_!!6000000004901-2-tps-173-209.png" alt="" srcset="">
    </div>
    <button id="button">dom转图片</button>
    </body>
    <script>
    const btn = document.getElementById("button");
    const ratio = ((document.documentElement.clientHeight || document.body.clientHeight) / (document.documentElement.clientWidth || document.body.clientWidth)) / (1624 / 750);


    btn.onclick = function () {
    document.body.scrollTop = document.documentElement.scrollTop = 0;
    const node = window.document.querySelector('.box');
    if (!node) {
    return;
    }
    let imgHeight = node.offsetHeight;
    let imgWidth = node.offsetWidth;
    let scale = window.devicePixelRatio;

    html2canvas(node, {
    useCORS: true,
    scale: scale,
    500,
    height: 500,
    backgroundColor: 'rgba(0, 0, 0, 0)',
    allowTaint: true,
    removeContainer: true,
    }).then((canvas) => {
    // const newCanvas = scaleCanvas(canvas, imgWidth * ratio, imgHeight * ratio);

    const image = canvas.toDataURL('image/png');
    console.log(image)
    })
    };

    </script>
    </html>
  • 相关阅读:
    Coursera台大机器学习课程笔记8 -- Linear Regression
    近两年跟踪速度较快的算法小结(转)
    hdu 4278 Faulty Odometer
    hdu 2571 命运
    hdu 6168 Numbers
    Codeforces 888C:K-Dominant Character
    poj 3061 Subsequence
    poj 1852 Ants
    1115. Counting Nodes in a BST (30)
    1064. Complete Binary Search Tree (30)
  • 原文地址:https://www.cnblogs.com/yujiawen/p/15348426.html
Copyright © 2011-2022 走看看