Encoding the img src is necessary when assigning it to an SVG element

I am encountering an issue with converting an SVG element generated by D3 into a PNG using dom-to-image within my Angular 2 application. The problem arises when I attempt to set the SVG as the source of an image element, resulting in the SVG code being encoded. How can I directly insert the unencoded string into the src?

Here is the code snippet that illustrates my approach:

var divelem = document.createElement('div');
var imgelem = document.createElement('img');
imgelem.height = 400;
imgelem.width = 300;
imgelem.src = node.outerHTML;
//imgelem.src = decodeURI(imgelem.src)

The node.outerHTML value is as follows:

[SVG code sample]

The current value of imgelem.src after setting it:

[Encoded URL]

Despite attempting to decode it, the URL remains invalid. As a result, I am unsure how to achieve placing the value from node.outerHTML into imgelem.src.

UPDATE:

I have tried directly assigning the SVG string to src, but regardless of what I do, the content gets encoded.

[SVG code sample]

Answer №1

To make it function properly, you must insert a string into the src attribute of your image. It is not feasible to include markup (or SVG in your case).

src: Represents a DOMString that mirrors the src HTML attribute, which contains the complete URL of the image including base URI.

Refer to the documentation for Image() here

Your top choice would be to utilize the data url syntax,
as illustrated in this sample:

var svg = '<svg width="166" height="195"><g trantsform="translate(86, ...></svg>'
var serializer = new XMLSerializer()
var data = serializer.serializeToString(svg)
yourImageElement.src = "data:image/svg+xml;charset=utf-8," + data

I trust this information proves helpful!

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

The best approach to typing a FunctionComponent in React with typescript

I'm diving into the world of React and TypeScript for the first time. Could someone verify if this is the correct way to type a FunctionComponent? type ModalProps = { children: ReactElement<any>; show: boolean; modalClosed(): void; }; co ...

Angular 2 forms are displaying ngvalid when input fields are marked as nginvalid

The form displays ngvalid because I have included the code like this: <form novalidate class="pop-form" (submit)="signUp()" #regForm="ngForm"> <div class="group"> <input type="text" [(ngModel)]="signUpData.name" [ngMode ...

Personalized ngIf directive featuring an included alternate template

In Angular applications, it is a common practice to use the ngIf directive with Observables to display data and provide an else template to show a placeholder while the data is loading. <data-view *ngIf="data$ | async as data; else progress" [items]="d ...

Build a module that includes both components and services

Currently, I am working on an Ionic 3 application and found the need for an accordion component similar to NgBootstrap's. Unfortunately, the Ionic framework does not offer such a component. This led me to take on the challenge of creating one myself, ...

What are the steps to enable full functionality of the strict option in TypeScript?

Despite enforcing strict options, TypeScript is not flagging the absence of defined types for port, req, and res in this code snippet. I am using Vscode and wondering how to fully enforce type checking. import express from 'express'; const app ...

Incorporate `swagger-ui-express` and `swagger-jsdoc` into your workflow both pre- and post-typescript compilation for optimal

In my project using TypeScript, path mapping, and esbuild for transpiling, I am trying to make both packages in the title work together. The swagger does not seem to work with the transpiled code. To transpile, I use the command rimraf dist && esbu ...

Encountering a cloning error while using React Typescript and React Router DOM when calling props.history.push

When using props.history.push without passing state, everything works perfectly fine. However, when trying to pass data with state, an error occurs. The error message reads: DOMException: Failed to execute 'pushState' on 'History': func ...

I am unable to utilize the Web Share API for sharing a file within my React app written in TypeScript

Trying to launch a WebApp for sharing files has been quite a challenge. After some thorough research, I stumbled upon the Web Share API which seemed like the perfect solution based on standard practices. The documentation provided a clear outline of how it ...

Extracting the "defined" type from a TypeScript property during runtime

My current task Presently, I am iterating through the keys of an object and transferring their values to another object. interface From { [key: string]: string; } let from: From = { prop1: "foo", prop2: "23", }; interface To { [key: str ...

Transitioning from angular 7 to the latest version 12

Upgrading from Angular 7 to 12 has presented a series of issues for me. The main problem seems to be with Angular Material. I am looking for a solution to this. ./src/app/material.module.ts:13:89-110 - Encounter Error: 'MatAutocompleteModule' ( ...

Is it possible for abstract classes to utilize arrays?

Can you have an array inside an abstract class in TypeScript and add items to it? abstract class Department { private data: string[] = []; addData(item: string) { this.data.push(item); } constructor(public name: string) {} printName(): ...

Creating reusable TypeScript function argument types

There is a function that I have defined in the following way: function getRangeBounds(start: number, stop?: number, step?: number) { if (step === undefined) step = 1; const actualStart = start !== undefined && stop !== undefined ? start : 0; ...

What steps are involved in generating a Typescript module definition for a directory containing a babel-plugin-content-transformer?

Currently utilizing the babel-plugin-content-transformer to import a directory containing YAML documents in a React Native/Expo project. The configuration for my babel plugin looks like this: ['content-transformer', { transformers: [{ ...

Is the client component not initializing the fetch operation?

On my page, there is a sidebar that displays items by fetching data successfully. However, when I click on one of the sidebar items to pass props to another component for fetching data, it doesn't fetch any data until I manually click the refresh butt ...

Is there a way to implement depth-first retrieval in rxjs using the expand method?

Currently, I am engaged in a project utilizing Angular 7, Typescript, and RxJS 6.3.3. In this project, I am working with RxJS Observables and relevant operators to handle hierarchical collections of objects obtained from an http server that interfaces with ...

Trouble with Nested Routing in React Router Version 6: Route not Rendering

I'm facing issues nesting a path within another path in react-router-dom version 6. When I try to visit the nested argument's page (/blog/1), it shows up as a blank non-styled HTML page. However, when I add a child path to the root like /blog, it ...

Can you explain the distinction between String[] and [String] in TypeScript?

Can you explain the distinction between String[] and [String] in typescript? Which option would be more advantageous to use? ...

Using Angular to condense or manipulate an array

I am working with a JSON response that contains arrays of arrays of objects. My goal is to flatten it in an Angular way so I can display it in a Material Table. Specifically, I want to flatten the accessID and desc into a flat array like [ADPRATE, QUOCON, ...

Dealing with the error "Type 'date[]' is not assignable to type '[date?, date?]' in a React hook

I'm attempting to assign a date range but encountering an error that states: Type 'Date[]' is not assignable to type '[Date?, Date?]'. Types of property 'length' are incompatible. Type 'number' is not assignab ...

Using source maps with Typescript in Webpack (source maps not visible while using webpack-dev-server)

I am currently experimenting with Typescript in combination with Webpack, utilizing the 'awesome-typescript-loader' plugin. However, I am encountering an issue where the source maps are not displaying in the browser when running webpack-dev-serve ...