How to save DIV as Image with HTM5 canvas to image with the extension?

Converting HTML DIV content to images is useful for generating reports, creating downloadable content, or saving visual elements. The html2canvas library makes this process straightforward by converting DOM elements into canvas, which can then be saved as images.

Installation

First, include the html2canvas library in your HTML:

<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>

Basic HTML Structure

Create a DIV with content you want to convert:

<!DOCTYPE html>
<html>
<head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
</head>
<body>
    <div id="cpimg" style="padding: 25px; background: #f0f8ff; border: 2px solid #4169e1; width: 300px;">
        <h4>Welcome to TutorialsPoint!</h4>
        <p>This DIV will be converted to an image.</p>
        <ul>
            <li>HTML Content</li>
            <li>CSS Styling</li>
            <li>Dynamic Elements</li>
        </ul>
    </div>
    
    <button onclick="saveAsImage()">Save DIV as Image</button>
    <button onclick="displayCanvas()">Show Canvas</button>

    <script>
        function saveAsImage() {
            html2canvas(document.querySelector("#cpimg")).then(canvas => {
                // Create download link
                const link = document.createElement('a');
                link.download = 'div-image.png';
                link.href = canvas.toDataURL('image/png');
                link.click();
            });
        }

        function displayCanvas() {
            html2canvas(document.querySelector("#cpimg")).then(canvas => {
                document.body.appendChild(canvas);
            });
        }
    </script>
</body>
</html>

Different Image Formats

You can save the DIV as different image formats:

<script>
function saveAsPNG() {
    html2canvas(document.querySelector("#cpimg")).then(canvas => {
        const link = document.createElement('a');
        link.download = 'div-image.png';
        link.href = canvas.toDataURL('image/png');
        link.click();
    });
}

function saveAsJPEG() {
    html2canvas(document.querySelector("#cpimg")).then(canvas => {
        const link = document.createElement('a');
        link.download = 'div-image.jpg';
        link.href = canvas.toDataURL('image/jpeg', 0.9); // Quality: 0.9
        link.click();
    });
}

function saveAsWebP() {
    html2canvas(document.querySelector("#cpimg")).then(canvas => {
        const link = document.createElement('a');
        link.download = 'div-image.webp';
        link.href = canvas.toDataURL('image/webp', 0.9);
        link.click();
    });
}
</script>

<button onclick="saveAsPNG()">Save as PNG</button>
<button onclick="saveAsJPEG()">Save as JPEG</button>
<button onclick="saveAsWebP()">Save as WebP</button>

Advanced Options

html2canvas accepts configuration options for better control:

<script>
function saveWithOptions() {
    const options = {
        backgroundColor: '#ffffff',
        scale: 2,                    // Higher resolution
        useCORS: true,              // Handle cross-origin images
        allowTaint: false,
        width: 400,
        height: 300
    };
    
    html2canvas(document.querySelector("#cpimg"), options).then(canvas => {
        const link = document.createElement('a');
        link.download = 'high-quality-image.png';
        link.href = canvas.toDataURL('image/png');
        link.click();
    });
}
</script>

<button onclick="saveWithOptions()">Save High Quality</button>

Error Handling

Always include error handling for robust applications:

<script>
function saveWithErrorHandling() {
    html2canvas(document.querySelector("#cpimg"))
        .then(canvas => {
            const link = document.createElement('a');
            link.download = 'div-image.png';
            link.href = canvas.toDataURL('image/png');
            link.click();
            console.log('Image saved successfully!');
        })
        .catch(error => {
            console.error('Error generating image:', error);
            alert('Failed to generate image. Please try again.');
        });
}
</script>

<button onclick="saveWithErrorHandling()">Safe Save</button>

Comparison of Image Formats

Format File Size Quality Browser Support
PNG Large Lossless All browsers
JPEG Medium Lossy All browsers
WebP Small Good Modern browsers

Conclusion

The html2canvas library provides an easy way to convert HTML DIV elements into downloadable images. Use PNG for high-quality images with transparency, JPEG for smaller file sizes, and WebP for the best compression in modern browsers.

Updated on: 2026-03-15T23:18:59+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements