JavaScript实现dom元素转图片

.html

<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>Documenttitle>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/dom-to-image/2.6.0/dom-to-image.min.js">script>
  <style >
    .box{
      width: 200px;
      height: 200px;
      background-color: red;
    }
  style>
head>

<body>
  <div class="box">div>
  <button class="btn">Downloadbutton>
  <script src="./index.js">script>
body>
html>

.js

const box = document.querySelector(".box");
const btn = document.querySelector(".btn");

btn.addEventListener("click", async () => {
  const res = await domtoimage.toPng(box);
  downloadImage(res);
});

const downloadImage = (imgsrc, name) => {
  let image = new Image();
  // 解决跨域 Canvas 污染问题
  image.setAttribute("crossOrigin", "anonymous");
  image.src = imgsrc;

  image.onload = function () {
    let canvas = document.createElement("canvas");
    const { width, height } = image;
    canvas.width = width;
    canvas.height = height;
    let context = canvas.getContext("2d");
    context.drawImage(image, 0, 0, width, height);
    let url = canvas.toDataURL("image/png");
    let a = document.createElement("a");
    let event = new MouseEvent("click");
    a.download = name || "photo";
    a.href = url;
    a.dispatchEvent(event);
  };
};

你可能感兴趣的:(JavaScript,javascript,前端,html)