html2canvas not rendering images properly

I've been attempting to utilize html2canvas to capture screenshots of specific components within my React application whenever a screenshot is taken, however, regardless of the various methods I've tried, the images produced always turn out blank.

Within the onClick listener for my screenshot button, this is the code that is implemented:

 const help = document.querySelector("#help");
html2canvas(help).then((canvas) => {
console.log(help, canvas);
const a = document.createElement("a");
a.href = canvas.toDataURL("image/png");
a.download = "help.png";
a.click();
});

This is what the element #help contains:

 <ul id="help">
<li>Lorem</li>
<li>lorem</li>
<li>lorem</li>
<li>lorem</li>
</ul>

The console.log statement confirms that the correct element is being selected through querySelector. I've experimented with altering properties like allowTaint, backgroundColor, foreignObjectRendering, and useCORS based on suggestions from other sources but none of these adjustments have resolved the issue for me. Even after removing all custom CSS styles, the problem persisted. Enabling logging did not provide any useful information either, leaving me at a loss regarding how to proceed.

Answer №1

Have you considered using the getElementById method? It should do the trick.

const renderPdf = () => {
    const targetElement = document.getElementById('headerr');
    html2canvas(targetElement).then((canvas) => {
        document.body.appendChild(canvas);
        var imgWidth = 210;
        var pageHeight = 295;
        var imgHeight = (canvas.height * imgWidth) / canvas.width;
        var heightLeft = imgHeight;
        const imgData = canvas.toDataURL('image/png');
        //window.open(imgData);
        const pdf = new jsPDF('p', 'mm');
        var position = -2;
        pdf.addImage(imgData, 'JPEG', 0, position, imgWidth, imgHeight);
        heightLeft -= pageHeight;

        /* add extra pages if the div size is larger than a a4 size */
        while (heightLeft >= 0) {
            position = heightLeft - imgHeight;
            pdf.addPage();
            pdf.addImage(imgData, 'JPEG', 0, position, imgWidth, imgHeight);
            heightLeft -= pageHeight;
        }
        pdf.save('file.pdf');
    });
};

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

Customize Individual Rows in a React DataGrid

I am exploring the world of Material UI React data grid for the first time, and I am looking to add a unique background color to only the initial three rows. Each row should have a different color scheme that remains static, without any interactions trigge ...

Encountering a compile error with a Next.js React project that cannot be resolved

Encountered an issue while refreshing my project with the command "npm run dev" and reloading the site locally. The console displays "Compiled /not-found" and the site fails to load completely. In addition, none of the elements animated via framer motion ...

Creating a see-through cursor resembling the one found on the App Store using CSS

Currently, I’m struggling a bit with understanding how to accomplish this task: The issue is that the pointer/arrow within the nav-element appears transparent and displays the content rather than its parent, which is the nav-element. Here is my HTML co ...

Troubleshooting issue in Next.js 9.4 with private route Higher Order Component and cookie authentication

Attempting to set up private (authenticated) routes in Nextjs using HOC and cookies, but encountering the following error: TypeError: Object(...) is not a function at export default withPrivateRoute(Private); I have confirmed that cookies are present els ...

Setting a default value when props are empty in reactJS - a guide

Incorporating both the default value and the value from my props for the background color is my goal. Currently, I am retrieving the value from the field in CMS Storyblok, which is a string. However, if I omit the default value, the background color of my ...

Aligning HTML Headings Vertically with CSS Baseline

I am looking to align two columns of headings to the baseline, with each having a different font size. Additionally, I want one column on the left side and the other on the right side. To achieve this, using display: inline-block will ensure that they are ...

Deciphering the intricacies of the http request

I encountered an issue while trying to send a POST request using jQuery AJAX. Upon making the request, I received the following error: XMLHttpRequest cannot load. Response for preflight has invalid HTTP status code 403 Now, I am unsure if the mistake i ...

Creating a Dynamic Soundtrack: How to Embed an Audio

Success! I finally figured it out, with a little help from everyone. I've been diving into the world of Audio Playlists in HTML and attempted to follow a tutorial on the topic found here: https://www.youtube.com/watch?v=vtZCMTtP-0Y. However, I encoun ...

Showing Angular 2 Data in JSON Format

When I retrieve an object with a Promise, it is structured as follows: export class ShoppingCart { Cart_Items: [ { Id: number, SKU: string, Link: string, ImageURL: string, Title: string, Description: str ...

Passing an array through ajax from PHP to JavaScript using a properly formatted JSON structure

I began with an array generated by PHP and retrieved via ajax, which had the following structure: Array ( [0] => {id:"12",from:"09:00:00",to:"15:00:00"} [1] => {id:"13",from:"08:00:00",to:"10:00:00"} [2] => {id:"12",from:"15:00:00",to ...

Retrieve the 'id' value located within the 'img' tag of HTML code by utilizing Beautiful Soup in Python

Given the following code snippet: id_image = soup.find_all("img")[2] print(id_image) The result is: <img id="nexperts-logo" src="images/nexperts.png"/> I am trying to extract and print only the id value, which is ...

Triggering blur event manually in Ionic 3

Is there a way to manually trigger the blur event on an ion-input element? The ideal scenario would be with an ionic-native method, but any javascript-based workaround will suffice. My current configuration: Ionic: ionic (Ionic CLI) : 4.0.1 (/User ...

Adjust the arrangement of divs when resizing the window

I have utilized flexbox to rearrange the boxes. Here is a link to the demo code My issue arises when resizing for smaller screens; I need to place B between A and C. https://i.stack.imgur.com/M0dpZ.png Any suggestions on achieving this goal? Thank you i ...

The Oracle Database listener is unaware of the service specified in the connect descriptor for node-oracledb

Having recently transitioned from on-premise databases using Oracle 11g to the Cloud where I needed to connect to Oracle 12c, I encountered an issue with my nodejs application. While it worked fine on-premises, in the cloud it threw the following error: e ...

What could be the reason for Sequelize to completely replace the record when updating in a put request?

I've been attempting to implement an "edit" feature within my project, but I've hit a roadblock in the process. Here's a snippet of the put request code: export const updateEvent = (event, id) => (dispatch, getState) => { request ...

Locking the second column of a data table with CSS to prevent scrolling

We need to freeze two columns in our data table - "PPD Delivery Schedule" and "Check Opex". The first column is working fine, but we're having issues freezing the second column. We've tried various approaches but haven't been successful so ...

Is there a way to prevent the entire form from being reset when providing initialValues for an array in final-form-arrays?

After implementing a form that utilizes final-form-arrays, I encountered an issue where making a state change within the component resulted in all values being reset, despite the form and validation functioning properly. To illustrate this problem, I recr ...

Using Node.js to parse JSON data fetched from the web

My current challenge involves retrieving and parsing JSON from a web API (https://api.coinmarketcap.com/v1/ticker/?limit=3) in order to extract the name and price_usd fields. For example: [ { ... sample data provided ... } ] The code snippet I am wo ...

Tips for retrying Ajax requests with references and incorporating success and failure handlers

I am currently testing the feasibility of storing a reference to an ajax call upon failure and then retrying the call at a later time. My attempt so far has been the following: $.ajax({ url: "controller/action", data: { params: "here" ...

How to Handle the Absence of HTML5 Spellcheck in Specific Web Browsers

While HTML5 spellcheck functionality may vary across different browsers, there are instances where it might not be supported in certain corporate environments. In the event that HTML5 is not supported in a particular browser, it's essential to first c ...