Get a Blob as a PNG File

Hope you had a wonderful Christmas holiday!

Just to clarify, I am new to JS and may make some unconventional attempts in trying to download my Blob in PNG format.

I am facing an issue with exporting all the visual content of a DIV in either PDF or image format upon clicking a button(the div has a consistent class name).

After researching, I learned that I need to convert the div to canvas for downloading it. I attempted to modify the code from this discussion: How to take screenshot of a div with JavaScript?

However, despite various tweaks and tests, nothing happens when I click on the button... Here's a snippet of my code:

<html lang="fr">
<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>Export Visualisation QS</title>
</head>
<body>
    <div class="qvt-sheet-container">
        <h1>EXPORT PNG</h1> 
        <img src="Logo-Qlik.png">
    </div>
    <a id="link"><button id="btn-export-qs">Export PNG</button></a>
</body>

<script language="JavaScript" type="text/javascript" src="jquery-3.6.0.min.js">
var a = document.getElementById("link");
function export_feuille() {
    $("#btn-export-qs").click(function() {
        html2canvas($(".qvt-sheet-container"), {
            onrendered: function(canvas) {
                //theCanvas = canvas;
                canvas.toBlob(function(blob) {
                    //saveAs(blob, "Dashboard.png");
                    url = window.URL.createObjectURL(blob);
                    a.href = url;
                    a.download = "export_qs.png";
                    a.click();
                    window.URL.revokeObjectURL(url);
                });
            }
        });
    });
};

document.getElementById("btn-export-qs").addEventListener ("click", export_feuille, false);

</script>
</html>

If anyone can offer insight into what might be going wrong or guide me in the right direction, I would greatly appreciate it :)

Answer №1

Upon reviewing your code, it seems that there is some redundancy present.

In the section of your code:

document.getElementById("btn-export-qs").addEventListener ("click", export_feuille, false);

The above snippet indicates that you are adding a click event listener to a button. When clicked, it calls the export_feuille function. However, within the export_feuille function, you are using jQuery to achieve the same functionality once again, which is unnecessary.

You have wrapped a <button> element inside an <a> tag. This setup utilizes the anchor tag unnecessarily to trigger the download event when the button is pressed. Here's a recommended modification:

HTML: I have removed the <a> tag

<div class="qvt-sheet-container">
    <h1>EXPORT PNG</h1>
    <img src="your-image.jpg" style="width: 150px;height: 150px">
</div>

<button id="btn-export-qs">Export PNG</button>

Javascript:

$("#btn-export-qs").click(function () {
    html2canvas(
        document.querySelector('.qvt-sheet-container'),
        {
            allowTaint: true,
            useCORS: true
        }
    ).then(canvas => {
        download(canvas)
    })
});

const download = function (canvas) {
    const link = document.createElement('a');
    link.download = 'filename.png';
    link.href = canvas.toDataURL()
    link.click();
}

Find the complete code here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The type 'myInterface' cannot be assigned to the type 'NgIterable<any> | null | undefined' in Angular

I am facing an issue that is causing confusion for me. I have a JSON data and I created an interface for it, but when I try to iterate through it, I encounter an error in my HTML. The structure of the JSON file seems quite complex to me. Thank you for yo ...

Achieve scrollability for right column (div) using Tailwind CSS

I am having trouble getting the content in the right column to scroll vertically. Can someone please help me identify what I'm doing wrong here? <link href="https://cdn.jsdelivr.net/npm/tailwindcss/dist/tailwind.min.css" rel="stylesheet"/> < ...

Styling images with text alignment in CSS

I'm trying to figure out how to align an image to the left, some text to the top right, and some text to the bottom right. The parent div contains a background image. <div id="parent" style="background: url(bg.jpg) repeat-x left top"> <i ...

How can I disable auto-fill for password input fields? Setting autocomplete="off" doesn't seem to be working

Hey there, I'm having some trouble with the autocomplete feature in Google Chrome. Can anyone suggest an alternative way to disable autocomplete for password fields? By the way, my project is using Vue.js. ...

Using PHP to perform live calculations with arrays in real time

Currently, I am working on developing a new system for a client that allows them to create bookings and invoices to send to their clients. One specific requirement my client has is the need for a table column to be added below the container columns in whi ...

Automatically update values in textboxes

Is there a way to dynamically adjust the input values so that they always add up to the total amount distributed? For example: Total: 50 Input1: 20 Input2: 15 Input3: 15 Are there JavaScript solutions available to achieve this? I am looking for a functio ...

Steps for modifying the CSS class of an <a> tag with Jquery/Javascript

I am attempting to dynamically change the class of a tab on the dashboard based on the selected page. In the dashboard, there are 3 tabs: <div> <ul class="menu"> <li class="MenuDashboard"><a href="#" >Dashboard</a&g ...

Personalizing the mat-checkbox

I'm trying to customize the checked icon in angular material mat-checkbox. Currently, it displays a white tick icon inside a colored background box, but I want to replace the tick with a cross when it is checked. After spending all day searching, I ha ...

Leveraging JS Variables within Twig Template

I am trying to incorporate a JavaScript variable into Twig. Despite attempting to implement the solution mentioned here, my code below does not render the map properly. If I remove the part between "var polylineCoordinates" and "polyline.setMap(map);", th ...

Images with full-width will scroll horizontally

Is there a way to fix the horizontal scroll issue? <!DOCTYPE html> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https:// ...

Creating movement effects for a line on an HTML5 canvas following a previous animation

I am facing an issue where my straight line starts animating towards the circle right at the beginning of page load. I am struggling with finding the logic to make the line animate in the opposite direction after the first animation is completed (which is ...

Refreshing and reloading within the same jQuery function

My PHP application involves the use of 2 PHP files. chart.php - This page includes a Google chart. <div id="chart_div" style="height:100%;width:100%"> </div> <script type="text/javascript"> google.charts.load('current', ...

Having trouble with functions in jQuery Ajax calls to ASMX files

I have a form in my web application that submits data through an ajax call to an asmx web service. The insertion of data into the database is successful, however, neither the success nor error function seems to be triggered afterwards. The first alert mess ...

The correct way to extract a jwt token from headers and integrate it into an express application

After successfully implementing both the frontend and backend in express.js with authentication and authorization using JWT, I have confirmed that the JWT token is being properly set upon login. You can see the auth-token key in the image below: https://i ...

I incorporated a CSS file from another HTML document. What do you think about that?

In my work with Ionic 3 and angular 4, each HTML file is accompanied by its own CSS file. There are times when I reference a class in one HTML file that is defined in another HTML file. I have observed that this CSS class gets injected into the main.js He ...

Is it possible to utilize the expose method to retrieve additional reactive variables and computed properties similar to methods in Vue 3?

Switching my application from Vue 2 to Vue 3 has been quite a journey. I've utilized the Composition API to refactor my previous render function into the setup hook. One interesting discovery was the ability to expose methods using context.expose({}). ...

Is the Date Epoch a reliable form of unique identification?

Currently, I'm developing a Node API and encountered a situation where I need to create a unique 15-digit random number for a model without using autoincrement. The challenge is to ensure that the generated number is not trivial. I am hesitant about ...

The onDrop event in javascript seems to be failing to execute

My attempts to get the javascript onDrop event to execute when an object is dropped into a drop zone have been unsuccessful. I've tried rewriting it in various ways without any success or error messages. In my search for potential reasons why the ondr ...

Is there a way to generate a distinctive curved design using CSS for a

I am currently using CSS and div elements in an attempt to create these particular lines: https://i.stack.imgur.com/Ytowq.png .line { width: 1px; height: 100px; background-color: black; position: absolute; border-radius: 50%/100px 1 ...

Setting up Visual Studio Code for debugging HTML and JavaScript code

Struggling to troubleshoot some HTML/JavaScript using VSCode. After installing the Chrome debugger extension and configuring the launch.json as follows: { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of ex ...