Get SVGImageElement for Canvas from embedded svg

  Kiến thức lập trình

How can I get an SVGImageElement from an SVG defined directly in the HTML that can be drawn on a Canvas?

HTML:

<div id="canvas-div">
   <canvas id="my-canvas">
   </canvas>
</div>

<div hidden>
   <svg width="100" height="100" id="svg-circle">
      <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
   </svg>
</div>

TS:

  let svgImagAny: any = document.getElementById("svg-circle");
  // let svgImg: SVGImageElement = svgImagAny as SVGImageElement; // Doesn't work
  this.context.drawImage(/* What goes here?*/ svgImg, 0, 0, 25, 25);

Edit: Thanks for the suggestion to look at How to access SVG elements with JavaScript? but this seems to rely on loading content. I specifically want to define the SVG entirely inline and then draw it on a Canvas. If I missed something there please point it out.

0

HTML:

<div id="canvas-div">
   <canvas id="my-canvas">
   </canvas>
</div>

<div hidden>
   <img src="/your/svg/path.svg" alt="Alternative text" id="svg-circle" />
</div>

TS:

 let svgImage = document.getElementById("svg-circle") as HTMLImageElement;
  this.context.drawImage(svgImage, 0, 0, 25, 25);

1

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT