I am experiencing difficulties saving the html2canvas image

Trying to use html2canvas to take a screenshot of a div element and save it, but encountering issues with the saving process.

function captureDiv() {
  const div = document.getElementById('myDiv');
  html2canvas(div, {
    scale: 2,
    onrendered: (canvas) => {
      let link = document.createElement('a');
      link.setAttribute('download', 'screenshot.png');
      link.setAttribute('href', canvas.toDataURL("image/png").replace("image/png", "image/octet-stream"));
      link.click();
    }
  });
}
div {
  width: 60px;
  height: 50px;
  text-align: center;
  border: 1px solid;
  line-height: 3;
}
<div> HI </div>
<button onclick="captureDiv()">Capture</button>

<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d2baa6bfbee0b1b3bca4b3a192e3fce2fce2ffa0b1fce7">[email protected]</a>/dist/html2canvas.min.js"></script>

Answer №1

You should use the then method to achieve this. According to information shared in this discussion, it replaces the onrederer function. Your code can be modified like this:

function captureDiv() {
  const div = document.getElementById('myDiv');

  html2canvas(div, {scale: 2}).then(canvas =>  {
    let link = document.createElement('a');
    link.setAttribute('download', 'screenshot.png');
    link.setAttribute('href', canvas.toDataURL("image/png").replace("image/png", "image/octet-stream"));
    link.click();
  });
}

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

Transferring data between actions following an AJAX request in Zend Framework

I am currently utilizing an ajax call to communicate with a controller in order to update the number of articles displayed on the webpage. I have established an action within the controller to handle this ajax request. Below is a snippet of the code: publ ...

What approach can be taken to optimize this promise error handling?

One common approach is to have a fallback solution in place. If the primary element fails to render, then it attempts rendering with alternative renderers. How can this be refactored for optimal performance? The issues with the current code are: Render ...

The jQuery change event functions smoothly on computers, but unfortunately, it fails to work on iOS devices

I've encountered an issue while developing a web application using Flask and jQuery. The change event works perfectly fine on PC web browsers, but it seems to be malfunctioning on iOS browsers. Let's take a look at the get_new_recipe_category.js ...

Resetting the Angular provider configuration whenever the service is injected into a different location

Trying to wrap my head around a rather complex issue here. I have a service set up as a provider in order to configure it. Initially, this service has an empty array of APIs which can be dynamically added to by various configuration blocks. When adding API ...

Passport authentication leading to incorrect view redirection in Express

I'm struggling to understand why the URL is updating but leading to the incorrect view. Once a user is authenticated with passport, the URL changes to my code (/clients) but it redirects back to the homepage view. After authentication, I want the us ...

In need of a collection of modules determined by a DefinePlugin constant

Currently, I am in the process of constructing a web application utilizing Webpack. However, I have encountered a challenge with a particular aspect of the design - hopefully someone in this forum has experience in similar tasks (or possesses enough knowle ...

Angular 4 with Universal: Implementing 404 Status Code in Header for /404 Page Component

After researching and reviewing numerous StackOverflow inquiries, I have come to the conclusion that headers are derived from responses served by servers, making it a non-issue. I attempted to rectify the situation from my server.ts file but unfortunately ...

Adding items from the JSON data to a nested array at index i

In my project, I am working with two files: index.js and list.json. My goal is to extract an element from list.json and insert it into a nested array following the structure [hour][visits per hour]. The hour refers to the index of the hour; for example, ...

What is the proper way to update data in reactjs?

I previously had code that successfully updated interval data in the browser and locale without any issues. class Main extends Component { constructor(props) { super(props); this.state = {data: []} } componentWillMount() { fetch('fi ...

Refreshing the page in VueJs does not trigger the axios function

I've encountered an issue with my VueJs app after purchasing the Vuexy template from ThemeForest. I created a new component called CountryTable.vue, and while it works initially, it fails to display data when I refresh the page. It only shows data whe ...

What is the best way to connect objects that have been separated?

Looking for a way to reattach my detached objects and wondering how to replace the function that currently only triggers an alert. Any suggestions or help is appreciated. http://jsfiddle.net/jy2Zj/ In addition, I have another question - is there a method ...

Most effective method for storing and retrieving data on the client side

In my ASP web application, I am facing a challenge with listboxes as changes in item selection happen frequently and quickly. This results in slow performance when trying to retrieve the necessary information through postbacks. So, I am trying to figure o ...

Create interactive highcharts graphs using data from a CSV file generated through PHP

I'm having trouble working with Highcharts and csv data. Take a look at this example: http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/line-ajax/ $.getJSON('http://www.highcharts.com/ ...

Interested in integrating server side JavaScript with your Android application?

Running a simple web page on a Raspberry Pi to toggle the board's LED with the click of a button. The button triggers a JavaScript function that controls the LED. Now, I want to be able to call this script from a button in an Android application... B ...

Understanding AngularJS and how to effectively pass parameters is essential for developers looking

Can anyone help me figure out how to properly pass the html element through my function while using AngularJS? It seems like this method works without AngularJS, but I'm having trouble with the "this" keyword getting confused. Does anyone know how I c ...

Ways to acquire ttf files from a third-party domain without encountering CORS issues

I am attempting to obtain a .ttf file from an external website for use in my web application. However, when I try the following code: @font-face { font-family: 'font'; src: url('http://xxx.xyz/resources/tipografias/font.ttf') forma ...

Achieving a draggable object to land on a designated target

Before you jump to conclusions based on the title, let me clarify that I am not referring to jQuery UI draggable. Instead, I am discussing a plugin that I am currently developing for the community. The goal of my plugin is to create a designated target fea ...

Is it possible to dynamically change the color of a box shadow using an event handler?

I'm currently in the process of developing an application that consists of six distinct topics organized within a flexbox structure, complete with a box-shadow effect. My objective is to dynamically alter the color of the box-shadow through an event ...

Utilizing class references within a method

I have been developing a script that is designed to dynamically load content into multiple predefined DIVs located in the topbar section of my website. Within the Topbar Object, there is an object called Ribbon which contains functions for manipulating on ...

How can I revert a date format using date-fns?

Greetings from Thailand! I have a question regarding the reverse formatting using date-fns. Is there a way to create a function that will change "saturday-9-september-2564" back to "2022-09-24" using date-fns? Any insights or methods on achieving this wo ...