Having trouble converting svg to png, thinking it might be due to discrepancies in svg elements

I am facing a puzzling issue where two different SVG elements are causing my JavaScript to work in one scenario but not the other. I have replaced the SVG elements in both examples, and surprisingly, only one works while the other does not. You can view the code in two separate jsFiddles, with the working example obtained from here.

My main objective is to save the current SVG element of a floor plan and insert the converted PNG as an inline image inside a rich text area. Imagine taking a cropped screenshot of the floor plan and pasting it into a rich text area similar to what you see on helpdesk sites. However, I am encountering difficulties in converting it to a PNG format.

Working Example: JsFiddle

Not Working Example: JsFiddle

Due to character limit constraints on Stackoverflow, I cannot include the SVG code here.

    var svgString = new XMLSerializer().serializeToString(document.querySelector('#svg2'));

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var DOMURL = self.URL || self.webkitURL || self;
var img = new Image();
var svg = new Blob([svgString], {
  type: "image/svg+xml;charset=utf-8"
});
var url = DOMURL.createObjectURL(svg);
img.onload = function() {
  ctx.drawImage(img, 0, 0);
  var png = canvas.toDataURL("image/png");
  document.querySelector('#png-container').innerHTML = '<img src="' + png + '"/>';
  DOMURL.revokeObjectURL(png);
};
img.src = url;

Edit:

After experimenting, I have settled on a code that excludes the PNG/canvas conversions and attempts to directly place the serialized SVG string into the rich text area. However, I encountered an error in IE stating "Non-default namespace declarations must not have an empty URI. Line: 1, column142".

var svgString = new XMLSerializer().serializeToString(document.querySelector('#svg2'));

var img = new Image();

var url = "data:image/svg+xml; charset=utf8, "+encodeURIComponent(svgString); 
img.onload = function() {

    document.querySelector('.ze_body').innerHTML = '<img src="'+url+'"/>';

};
img.src = url;

To provide more context, I believe it would be beneficial to show the structure in which the rich text area currently exists. This layout is pre-existing in a product we utilize, and I am attempting to embed maps into the description area for better ticket management. Our access is limited to using JavaScript triggered through form rules.

Screenshot of ze_body element within the DOM for reference

Answer №1

The origin of this issue lies in your namespace declaration :

To resolve the problem, update

xmlns:NS1="" NS1:xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:NS2="" NS2:xmlns:cc="http://creativecommons.org/ns#" xmlns:NS3="" NS3:xmlns:dc="http://purl.org/dc/elements/1.1/"

with

xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:cc="http://creativecommons.org/ns#" xmlns:dc="http://purl.org/dc/elements/1.1/">

This adjustment should successfully resolve the issue. See it in action here.

For a more detailed explanation on namespace declarations, refer to this resource.

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

deleting hyperlink on mobile device

I'm trying to hide a specific div when the screen size is mobile, and currently I have: HTML <div id='top-btn'> <a class="fade-in" href="...">Top</a> </div> CSS #top-btn a { visibility: visible; opacity: 1 ...

What is the process for defining a date range in HTML5?

I am currently working on a wedding website and I am trying to set up a countdown for the wedding date. However, I am having trouble figuring out how to correctly display the countdown. https://i.sstatic.net/iGikh.png Here is the code snippet that I am u ...

Maintain visibility of the vertical scroll bar while scrolling horizontally

Currently, I am in the process of setting up a table with fixed headers and columns that have a minimum width. To ensure this setup functions correctly, I require both vertical and horizontal scroll bars. The vertical scroll bar should only navigate throu ...

Ways to remove unnecessary div containers in Nuxt js?

This is an example of my page: https://i.sstatic.net/CYCRL.png Showing the Nuxt layout: <template> <div> <Nuxt /> </div> </template> After being compiled by Nuxt, it generates: https://i.sstatic.net/CYdX3.png You ...

Refresh React Components on the Fly (Solr)

I am relatively new to ReactJS In my React class, I have a function that is rendering multiple items: (Sample) var app = app || {}; app.Results = React.createClass({ componentDidMount: function () { }, handleUpdateEvent: function(id) ...

How can the caption be aligned to the right of the image within a Bootstrap thumbnail in a precise manner, while also ensuring the button is positioned at the bottom of the caption?

Greetings! I am in the process of developing a website using bootstrap v3.3.2. My first query revolves around utilizing the grid system to correctly position the caption on the right side of the thumbnail, as illustrated below: <div class="container"& ...

Updating partial data in MVC without having to reload the entire HTML content is a straightforward process that

I am looking to update partial view data without refreshing the HTML. I have utilized Json to fetch the data, but it seems like there might be some issues in the script. The Success part is not being executed. [HttpPost] public ...

Removing the Tawk.to integration in React Redux using external JavaScript

Seeking help with integrating the Tawk.To Widget into my React APP. The widget (javascript) loads successfully when the page is first opened, but remains present when navigating to another page. How can I properly unmount this script when moving to a diff ...

Vue Pinia ensures that reactive state is only updated once, preventing unnecessary updates

In my Vue application, the structure is as follows: App.vue -GroupWrapper --GroupListing -PeopleWrapper --PeopleListing -ConversationWrapper Within my user store that utilizes Pinia, I primarily call user.findChats() in the App.vue component. Code snippe ...

Tips for utilizing two renderCell functions in a datagrid from Material UI without encountering duplication or repetition

Utilizing Material UI, I have designed a table to showcase my data. In this setup, I am required to use renderCell for two specific properties: 'level by user' and 'level by referent'. Issue: The problem arises when Material UI displa ...

Is it possible to modify the font size of all text that shares a particular font size?

Lately, I've been pondering on a question. A few years ago, I created a website using regular CSS and now I want to make some changes to the font sizes. While I know that CSS variables are the recommended solution for this situation, I'm curious ...

Neglectful TypeScript null checks overlooking array.length verification

When TypeScript is compiled with strict null checks, the code snippet below does not pass type checking even though it appears to be correct: const arr: number[] = [1, 2, 3] const f = (n: number) => { } while (arr.length) { f(arr.pop()) } The comp ...

Tips on eliminating overlapping strokes

I'm having trouble with drawing an array of circles that are meant to intersect a series of lines. The issue I face is that if the circles overlap, a stroke appears underneath them which I want to remove. Does anyone have any suggestions on how to el ...

CSS Drop-Down Menu Fails to Function Properly in Firefox and Internet Explorer

Can you help me with this issue I'm having with my website design? In Google Chrome, Opera, and Safari, everything looks great. But in Firefox and the latest version of IE, it's a different story. Here is the HTML code: <div id="navbar"> ...

ContainerView: challenges encountered when dynamically inserting views

ContainerView.pushObject() does not automatically connect dynamically added views with a Container object. The absence of an auto-wired container leads to a rendering error when a view renders a template containing a handlebars render helper. SIMPLE SCENA ...

Obtaining the MasterTableView Edit Form within a Radgrid to acquire a reference to a textbox

Can anyone help me with two things, please? I am struggling to access the currently edited existing row in the Radgrid and also the index of the Edit form when attempting to add a new record to the table. function OnClientSelectedIndexChanged(sen ...

Instructions for converting a readonly text field into an editable one using JavaScript

I'm trying to make it so that when the button (with id name_button) is clicked, the text field (with id name_text_field) becomes enabled. However, my current code doesn't seem to be working. Here's a snippet of my HTML: <input type="tex ...

Observing changes in the height of an Angular directive

I've encountered an issue where I can't seem to get the code working properly even though the question has been asked before. Within my directive, I have found that the following piece of code functions correctly when the element's height i ...

Dynamic loading of JavaScript/HTML content using jQuery Mobile and PhoneGap

I am currently in the process of building a mobile app using Dreamweaver CS6 (with PhoneGap), along with jQuery Mobile and JavaScript. This app aims to gather user-inputted form data, convert it into a JSON object, and send it to a python web service. The ...

What's the best way to make sure my table fits perfectly within its container's width?

I've encountered an issue with a table: If you want to see how the table was created, check it out on jsFiddle I attempted to modify the CSS like this : table{ width:100%; } td span { float:right; width:20%; text-align:center ...