A step-by-step guide on converting SVG to PNG format with canvg.js and Canvas

We are attempting to convert an SVG image to PNG using canvg.js, but upon clicking the button labeled "Take a screenshot", an error is displayed in the console stating "vue.runtime.esm.js?2b0e:619 [Vue warn]: Error in v-on handler: "ReferenceError: SVG2PNG is not defined"". The button triggers the function "tipka()", following the example provided at .

<input id='downloadBtn' @click="tipka()" type='button' style="margin-top:500px; position:absolute" value='Download'/>

Below is the script file:

import Canvg from "canvg";

export default {
  methods: {
    SVG2PNG(svg, callback) {
      var canvas = document.createElement("canvas"); // Create a Canvas element.
      var ctx = canvas.getContext("2d"); // For Canvas returns 2D graphic.
      var data = svg.outerHTML; // Get SVG element as HTML code.
      canvg(canvas, data); // Render SVG on Canvas.
      callback(canvas); // Execute callback function.
    },
    generateLink(fileName, data) {
      var link = document.createElement("a");
      link.download = fileName;
      link.href = data;
      return link;
    },

    tipka() {
      var element = document.getElementById("svg-01"); // Get SVG element.
      SVG2PNG(element, function (canvas) {
        // Arguments: SVG element, callback function.
        var base64 = canvas.toDataURL("image/png"); // toDataURL return DataURI as Base64 format.
        generateLink("SVG2PNG-01.png", base64).click(); // Trigger the Link is made by Link Generator and download.
      });
    },
  },
};

Answer №1

Avoid including SVG2PNG in the exported methods object. It is more efficient to access it directly with just SVG2PNG().

Similarly, the same concept applies to generateLink.

Simply stick to the following structure:

import Canvg from "canvg";

function SVG2PNG(svg, callback) {
  var canvas = document.createElement("canvas"); // Create a Canvas element.
  var ctx = canvas.getContext("2d"); // For Canvas returns 2D graphic.
  var data = svg.outerHTML; // Get SVG element as HTML code.
  Canvg(canvas, data); // Render SVG on Canvas.
  callback(canvas); // Execute callback function.
}

function generateLink(fileName, data) {
  var link = document.createElement("a");
  link.download = fileName;
  link.href = data;
  return link;
}

export default {
  methods: {
    tipka() {
      var element = document.getElementById("svg-01"); // Get SVG element.
      SVG2PNG(element, function (canvas) {
        // Arguments: SVG element, callback function.
        var base64 = canvas.toDataURL("image/png"); // toDataURL return DataURI as Base64 format.
        generateLink("SVG2PNG-01.png", base64).click(); // Trigger the Link is made by Link Generator and download.
      });
    },
  },
};

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

Issue with ng-cloak not resolving flicker on button in Chromium; strangely, ng-cloak CSS doesn't apply as expected

Here is a snippet of my HTML code: <button type="button" class="btn btn-primary ng-cloak" ng-click="ctrl.add(ctrl.userProfile.username)" ng-hide="ctrl.userProfile.added">Add</button> The code above is a part of the larger HTML document shown ...

Specify the return type based on specific parameter value

I'm facing a situation where I have two definitions that are identical, but I need them to behave differently based on the value of the limit parameter. Specifically, I want the first definition to return Promise<Cursor<T>> when limit is g ...

JavaScript interprets code differently each time it runs

After returning to work this morning, I encountered some strange behavior that disappeared after restarting the server. Despite my efforts, I couldn't recreate it. So, consider this question "solved" and feel free to delete it if necessary. I'm n ...

What steps are needed to set up my Express server so that it can render all my content, rather than just my HTML file?

I need help setting up a server for my project using Express. Here is the structure of my file directory: root-directory ├── public │ ├── css │ │ └── styles.css │ ├── images │ │ └── img1.png | | └ ...

What is the best way to trigger ajax when the user clicks the back button to return to the previous webpage?

Check out my code snippet below: HTML Code <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="body"> <div class="dropdown_div"> <select id="q_type" class="dropdown" ...

What is the process for declaring an exported type variable in React?

I have created a unique configuration in a different file: //config.js export const config = [ { id:0, name:"Config 1", }, { id:1, name:"Config 2", }, { id:2, name ...

In a React app, there are instances where `localstorage.getitem('key')` may result in returning null

I've encountered a strange issue while building a login form that sets a JWT token in localstorage. The problem arises when, despite being able to see the token in my console.log, setting localstorage.getitem('idToken') sometimes returns nul ...

Add the onclick() functionality to a personalized Angular 4 directive

I'm facing an issue with accessing the style of a button in my directive. I want to add a margin-left property to the button using an onclick() function in the directive. However, it doesn't seem to be working. Strangely, setting the CSS from the ...

The pagination in Laravel Vue is causing a validation error due to an invalid prop type check failing

Recently, I delved into working with Nuxt.js and decided to install the Laravel-Vue-Pagination plugin. However, I encountered an error message in my console system that reads: [Vue warn]: Invalid prop: type check failed for prop "data". Expected Object, ...

What is the best way to create height segments from a cylinder in three.js?

My current project involves a cylinder that is divided into multiple height segments, with the number of segments depending on the specific data. Each height segment contains a value that I want to use for extruding the entire circle at that particular hei ...

What are the implications of a project containing nested node_modules directories?

We are currently in the process of dividing our project into "sub modules" within a single repository. Our goal is to maintain aspects such as webpack configurations and express server globally, with a structure similar to the following: package.json serv ...

Error: Trying to access the length property of an undefined or null reference in JSON formatted data fetched through Ajax

I am attempting to populate a jQuery DataTables with JSON data retrieved from a Web API ajax call, but encountering the following error: An unhandled exception occurred at line 38, column 314 in 0x800a138f - JavaScript runtime error: Unable to get proper ...

Generating variable names dynamically in JavaScript

To prevent a javascript heap issue, I implement the usage of multiple arrays including 'family1', 'family2','family3' and 'dogs1', 'dogs2', 'dogs3'. For instance, you can use 'family1 and dog ...

In the iOS app when the Ionic HTML5 select keypad is opened, a bug causes the view to scroll upwards and create empty space after tapping the tab

I am currently working with Ionic v1 and AngularJS, utilizing ion tabs: <ion-tabs class="tabs-icon-top tabs-color-active-positive"> <!-- Home Tab --> <ion-tab icon-off="ion-home" icon-on="ion-home" href="#/tab/home"> <ion-nav ...

Ways to organize backbone models, views, and collections using vim?

I am a fan of vim's folding feature, but I have encountered some challenges when trying to fold backbone models, views, and collections. This is because backbone does not follow the traditional prototype syntax, but instead uses a .extend() based synt ...

Node.js CallbackHandler: Simplifying event handling in JavaScript applications

I implemented the following function in a .js file to handle an asynchronous network connection: function requestWatsonDiscovery(queryString) { console.log('Query =', queryString); if (typeof queryString !== 'undefined') { ...

Lazy loading a React grid gallery as you scroll

Currently, I am utilizing React grid gallery to showcase images from this repository: https://github.com/benhowell/react-grid-gallery. However, I am encountering an issue with lazy loading when the user scrolls on the page. <Gallery images={this ...

Having trouble with the response from the Object object?

Can someone assist me with the response I am getting here? I am receiving a response from an API call and trying to store the results from screen_results. However, when I attempt to print it out, all I see is [Object object]. I have tried to stringify it, ...

The art of encapsulating JSON response objects in Ember Objects with a deep layer of wrapping

Currently, I am engaged in a project using Ember where I retrieve a complex JSON response in a Route's model function. In the associated template, I exhibit attributes of the response. Some of these attributes allow for specific actions that result in ...

Switch the style of a set of thumbnail images when clicked

I am working with a set of thumbnails where one has an "p7_current" class applied, giving it a border, while the rest have an "p7_inactive" class removing the border. My goal is to have the last clicked thumbnail in a group of 6 to have the "p7_current" c ...