Convert div container to full HD image download using React JS

Convert div container to full HD image download using React JS

Table of contents

In web development, it's common to use div containers to structure and style content on a webpage. However, sometimes there is a need to convert a specific div container into an image for various reasons, such as generating a thumbnail or sharing content on social media platforms.

In this article, we will explore how to convert a div container to a full HD image download using React JS. We will cover the necessary steps and provide sample code to guide developers through the process. By the end of this article, readers will have a better understanding of how to leverage React JS to create high-quality images from div containers on their web pages.

Start Coding

To convert a div container to a full HD image and enable downloading of the image using React, you can use the html2canvas library to generate a screenshot of the container, and then use the FileSaver.js library to trigger the download.

npm i html2canvas
npm i file-saver

Here's an example code:

import React from "react";
import html2canvas from "html2canvas";
import { saveAs } from "file-saver";

class DownloadButton extends React.Component {
  handleDownload = () => {
    const container = document.getElementById("my-container");

    html2canvas(container, {
      scale: 25, // Set scale to 25x for full HD resolution (1920x1080)
      useCORS: true // Enable CORS to allow screenshot of external images
    }).then(canvas => {
      canvas.toBlob(blob => saveAs(blob, "download.png"));
    });
  };

  render() {
    return (
      <>
        <div id="my-container">
          <h1>hello</h1>
          <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Autem at nostrum quas pariatur incidunt error voluptate illo exercitationem corrupti similique!</p>
        </div>
        <button onClick={this.handleDownload}>Download Image</button>
      </>
    );
  }
}

export default DownloadButton;

In this example, we create a DownloadButton component that includes a div container with an id of my-container, which we will use to capture a screenshot. When the user clicks on the download button, we use the html2canvas library to generate a screenshot of the container, and then convert it to a Blob object and trigger the download using the saveAs function from the FileSaver.js library.

Note that we set the scale option of the html2canvas function to 25, which will generate a full HD (1920x1080) image. We also set the useCORS option to true to enable the capture of external images that may be displayed within the container.

Make sure to include the html2canvas and FileSaver.js libraries in your project by installing them via npm and importing them at the top of your file:

Demo

Did you find this article valuable?

Support Amit Gajare by becoming a sponsor. Any amount is appreciated!