Screen capture (convert HTML elements into images for download)

Scene:

I wrote a div to make posters, business cards and so on. I need to intercept it and download it

<style>
  .box {
    width: 300px;
    height: 300px;
    background-color: red;
  }
</style>

<div class="box"></div>
<button>Generate business card</button>
Copy the code

Implementation:

  1. The html2Canvas plugin is introduced to convert HTML elements to canvas

npm i html2canvas

// Return a promise with a canvas as the res argument
html2canvas(document.querySelector('.box'))
Copy the code
  1. Write a method pair to download the Canvas element
function downloadCanvas(canvas) {
  // Call the Canvas toDataUrl method to turn the Canvas into an image. The argument is the image format. The default is 'image/ PNG '.
  const canvasUrl = canvas.toDataURL()
  // Generate a tag for download
  const oA = document.createElement('a')
  // Set the file name for the download. Default is' download '.
  oA.download = ' '
  oA.href = canvasUrl
  document.body.appendChild(oA)
  oA.click()
  // Delete the created element after downloading
  oA.remove()
}
Copy the code

The complete code

<style>
  .box {
    width: 300px;
    height: 300px;
    background-color: red;
  }
</style>

<div class="box"></div>
<button>Generate business card</button>

<script>
  document.querySelector('button').addEventListener('click'.() = > {
    html2canvas(document.querySelector('.box')).then((canvas) = > {
      // Call the Canvas toDataUrl method to turn the Canvas into an image. The argument is the image format. The default is 'image/ PNG '.
      const canvasUrl = canvas.toDataURL()
      // Generate a tag for download
      const oA = document.createElement('a')
      // Set the file name for the download. Default is' download '.
      oA.download = ' '
      oA.href = canvasUrl
      document.body.appendChild(oA)
      oA.click()
      // Delete the created element after downloading
      oA.remove()
    })
  })
</script>
Copy the code