简体   繁体   中英

How to convert SVG to Base64 string in Angular

i want to convert an svg element to a base64 string.

i followed following tutorial: https://thewebdev.info/2021/08/28/how-to-convert-inline-svg-to-base64-string-with-javascript/

this is the code i used:

HTML:

<svg height="100" width="100">
  <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
</svg>

TypeScript:

constructor (
  @Inject(DOCUMENT) document: Document
) {
  document.querySelector("svg")
}

ngOnInit() {
  const s = new XMLSerializer().serializeToString(document.querySelector("svg"))
  const encodedData = window.btoa(s)
  console.log(encodedData)
}

but i get following error message in vs code at .serializeToString(document.querySelector("svg")) :

Argument of type 'SVGSVGElement | null' is not assignable to parameter of type 'Node' TS 2345

The issue here is that svg isn't initialized when ngOnInit is called, hence querySelector returns null.

Move your code in ngAfterViewInit like below:-.

ngAfterViewInit() {
  const svg = document.querySelector("svg");
  if (svg) {
     const s = new XMLSerializer().serializeToString(svg)
     const encodedData = window.btoa(s)
     console.log(encodedData)
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM