Html2Canvas failed to save the image

Can someone help me troubleshoot the issue I'm having with capturing an image using HTML2Canvas library? The code below includes a tab with an image inside it, but for some reason, the image is not being captured when I try to download the entire div.

I've attempted to add the configuration option allowTaint:true, but I keep getting this error message

DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
. I'm unsure why this problem persists, and any assistance would be greatly appreciated. Thank you.

function sendData() {
    html2canvas(document.getElementById('capture')).then(function(canvas) {
      $('#test').append(canvas);
      $('#test').attr('href', canvas.toDataURL('image/png'));
      $('#test').attr('download', 'Test.png');
      $('#test')[0].click();
    });
  }


  function openCity(evt, cityName) {
    var i, tabcontent, tablinks;
    tabcontent = document.getElementsByClassName("tabcontent");
    for (i = 0; i < tabcontent.length; i++) {
      tabcontent[i].style.display = "none";
    }
    tablinks = document.getElementsByClassName("tablinks");
    for (i = 0; i < tablinks.length; i++) {
      tablinks[i].className = tablinks[i].className.replace(" active", "");
    }
    document.getElementById(cityName).style.display = "block";
    evt.currentTarget.className += " active";
  }

  document.getElementById("defaultOpen").click();
body {
      font-family: Arial;
    }
    
    .tab {
      overflow: hidden;
      border: 1px solid #ccc;
      background-color: #f1f1f1;
      margin-top: 10px;
      border-top-left-radius: 8px;
      border-top-right-radius: 8px;
    }
    /* Style the buttons inside the tab */
    
    .tab button {
      background-color: inherit;
      float: left;
      border: none;
      outline: none;
      cursor: pointer;
      padding: 14px 16px;
      transition: 0.3s;
      font-size: 17px;
      border-bottom: 8px;
    }
    /* Change background color of buttons on hover */
    
    .tab button:hover {
      background-color: #ddd;
    }
    /* Create an active/current tablink class */
    
    .tab button.active {
      background-color: #ccc;
    }
    /* Style the tab content */
    
    .tabcontent {
      display: none;
      padding: 6px 25px;
      border: 1px solid #ccc;
      border-top: none;
      -webkit-animation: fadeEffect 1s;
      animation: fadeEffect 1s;
      border-bottom-left-radius: 8px;
      border-bottom-right-radius: 8px;
      background-color: white;
    }
    
    .jobs-panel {
      display: table;
      max-height: 100%;
      width: 85%;
      background-color: #b7bcbe;
      margin-left: auto;
      margin-right: auto;
      margin-top: 25px;
      margin-bottom: 25px;
      padding-bottom: 20px;
      padding-top: 20px;
    }
    
    .tabwidth {
      width: 85%;
      margin: 0 auto;
    }
<!DOCTYPE html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>

<head>
  <meta charset="utf-8" />
 
  <link rel="shortcut icon" href="//#" />
  <script type="text/javascript" src="https://html2canvas.hertzen.com/dist/html2canvas.js"></script>
  <script type="text/javascript" src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
</head>

<body>
  <div id="capture">
    <h1>Hello My man</h1>
    <div class="jobs-panel">

      <p>In this example, we use JavaScript to "click" on the London button, to open the tab on page load.</p>

      <div class="tabwidth">
        <div class="tab">
          <button class="tablinks" onclick="openCity(event, 'London')" id="defaultOpen">London</button>
          <button class="tablinks" onclick="openCity(event, 'Paris')">Paris</button>
          <button class="tablinks" onclick="openCity(event, 'Tokyo')">Tokyo</button>
        </div>

        <div id="London" class="tabcontent">
          <h3>London</h3>
          <img src="https://cdn.bulbagarden.net/upload/thumb/4/49/Ash_Pikachu.png/250px-Ash_Pikachu.png" width="300" height="300">
          <p>London is the capital city of England.</p>
        </div>

        <div id="Paris" class="tabcontent">
          <h3>Paris</h3>
          <p>Paris is the capital of France.</p>
        </div>

        <div id="Tokyo" class="tabcontent">
          <h3>Tokyo</h3>
          <p>Tokyo is the capital of Japan.</p>
        </div>
      </div>
    </div>
  </div>
  <div id="match-button" onclick="sendData();">capture</div>
  <a id="test" href="#"></a>
</body>

</html>

Answer №1

modify

<img src="https://cdn.bulbagarden.net/upload/thumb/4/49/Ash_Pikachu.png/250px-Ash_Pikachu.png" width="300" height="300">

into

<img src="https://cdn.bulbagarden.net/upload/thumb/4/49/Ash_Pikachu.png/250px-Ash_Pikachu.png" width="300" height="300" crossorigin>

and adjust your JavaScript to include allowTaint: false;

this should resolve the issue,

update jsfiddle -> http://jsfiddle.net/qp4b8frw/14/

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

Eliminate objects that have been clicked and deleted using the delete button component from the ul list using the filter feature in Vue

I've encountered an issue with Vue.js. Despite trying various methods I found, I'm unable to delete an element. I even consulted a chat GPT for assistance, but unfortunately, the provided answer did not solve my problem. Below is the code snippe ...

The optimal method to showcase lists of names: HTML or CSS?

I have a roster of 40 individuals, complete with their titles and additional details akin to a yearbook layout without the actual photos. Previously, I relied on HTML tables to format this information, but I am contemplating whether there might be a more e ...

creating a distinctive JSON data structure in Node.js

I have a JSON dataset that looks like this, var data = [ { _id: 5abb46b060808f3a2096f91d, patient_name: 'krishnaaaannnn', gender: 'male', charge_id: 5ab243ac73959deb3ad79fec, description: 'suffering from pain' ...

Do JavaScript functions in separate <script> tags exist in the global scope?

Here's a scenario I'm dealing with in an HTML file: <script> var my_function = function(param) { alert(param); } </script> <div> <!-- snip --> <script> $(function() { my_function("Hello wor ...

Struggling to determine whether an array contains data or is void in ReactJS?

In the state, I have an array and I set the default value of my state to an empty array []. After loading an API request, I need to display a loader until the data is ready. So, I am using a condition like this: (if the array length === 0, the loader wil ...

Determining the Similarity of jQuery Selectors' Selected Elements

I'm looking for a way to programmatically identify if two jQuery selectors have chosen the exact same element. My goal is to iterate over multiple divs and exclude one of them. This is what I envision: var $rows, $row, $row_to_exclude; $rows ...

What is the best way to implement a Navbar link in React.js?

I am currently working on developing a website using Reactjs. I have successfully created a Navbar with two links - Home and Contact. However, when I click on the Contact link, although the URL changes accordingly, the page itself does not update. I have s ...

Using CSS grid can allow for paragraphs to overlap on top of each

https://i.sstatic.net/LVsgQ.jpgCurrently working on constructing a biography page filled with text content, and I aim to utilize CSS GRID instead of floats. I encountered an issue in getting the text to occupy all the available white space within the layou ...

JavaScript implementation of Content-disposition feature

Is it possible to use client-side JavaScript to make the browser behave the same way as when it encounters "Content-disposition: attachment; filename=..."? This would mean that the data for the file to be saved is only available on the client side. For ex ...

"Unlocking the Power: Bringing Data from the Backend to the Frontend with ASP.NET OnClick

As I delve into the code of my current project, I find myself deciphering the work of a previous developer. Specifically, I am grappling with the usage of Eval in HTML forms. Within my HTML form, there is an onclick action that triggers the download of a ...

Make multiple images in one row resize proportionally instead of wrapping them to the next line

My phone's screen is small and I want the three images to remain in the same row. In case they don't fit, they should shrink proportionately to maintain alignment (refer to image at the bottom). Consider the code snippet below: <div id="exam ...

Using Ionic to invoke a function within another function in a JavaScript service

Hey everyone, I've come across an issue while working on my Ionic mobile app project. I need to call a function within another function in one of my service.js files (pushNotificationService.js). Here is the code snippet: checkForNewMessage: functi ...

The redirection of the URL after form submission is not functioning correctly

I'm attempting to develop a pair of dropdown lists in Elementor where the second dropdown's options depend on what is selected in the first, and the second contains URLs linked to a GO button that redirects to the chosen URL. However, I've f ...

Should I save exclusive items as an object or an array?

In the process of creating a compact online store system with MongoDB integration, there is an order table set up to house various items. Each individual item possesses a unique trait known as code. The dilemma arises when deciding on how the data should ...

Is there a way to change this from webkit to moz?

Is there a way to change this code from webkit to moz? background-color: #fff; background-image: -moz-linear-gradient(0deg, transparent 79px, #ABCED4 79px, #ABCED4 81px, transparent 81px), -moz-linear-gradient(#EEE .05em, transparent .05em); ...

What causes the unexpected behavior of str.replace() when the replacement string contains a regex pattern?

let a = `<script crossOrigin="anonymous" src="//example.com/index.js"></script>` let regex = new RegExp( `<script(.*?) src="` + '//example.com/index.js' + `"></script>`, 'g') let replacementString = ...

Discover the method for displaying a user's "last seen at" timestamp by utilizing the seconds provided by the server

I'm looking to implement a feature that displays when a user was last seen online, similar to how WhatsApp does it. I am using XMPP and Angular for this project. After making an XMPP request, I received the user's last seen time in seconds. Now, ...

Using Vue.js: How to Trigger a Child Method from the Parent Component

I recently explored the communication between components using vuejs and vuex. Here is a scenario I encountered: The first component is a menu The second component, nested within the first, is a hamburgerButton. In this specific case, when I click the ...

Retrieving and assigning data values within an Angular JS service

Here is the service I created to fetch user details: angular.module('app') .factory('userDetailService', function($http) { var userData = {}; function getUserDetails(userId) { if (userId) { return $http.get ...

I am encountering a continuous css ParserError while trying to compile my react project

I'm having trouble with the compilation of my React project. While everything runs smoothly with npm start, I encounter an error during compilation: npm run build <a href="/cdn-cgi/l/email-protection" class="__cf_ema ...