2

How Can I draw this svg on a Canvas using Javascript (Without using Dom) ?

<svg width="100" height="100">
   <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
   Sorry, your browser does not support inline SVG.
</svg> 

Note: Answers in post this and this Only give a solution when you have an external SVG. My requirement is to draw multiple svgs on Canvas (or anything else) with variable x,y, radius and color

dota2pro
  • 7,220
  • 7
  • 44
  • 79
  • 1
    https://stackoverflow.com/a/25095549/8620333 ? – Temani Afif Aug 14 '19 at 21:23
  • @TemaniAfif this is not an SVG I want to draw SVG so that On zoom it does not pixelate. this will pixelate on zoom – dota2pro Aug 14 '19 at 21:24
  • from what I know this not the pupose of canvas. SVG is made for scalable vector and canvas is made for bitmap and pixel by pixel rendring. (https://www.educba.com/svg-vs-canvas/). Even if you draw the content of an SVG inside a canvas you will still have issue with zomming – Temani Afif Aug 14 '19 at 21:27
  • from the link above : *SVG does not depend on the resolution, means it is resolution independent. If we enlarge the image, it will not lose its shape. Canvas is resolution dependent. If the image is enlarged, it will start reflecting the pixels of the image.* – Temani Afif Aug 14 '19 at 21:28
  • @TemaniAfif is there an alternative for that ? how can I make a scalable canvas like thing using javascript I need to pass x,y dynamically to it – dota2pro Aug 14 '19 at 21:36
  • You clearly don't need canvas. What you need is SVG. I guess you have to re-think your choices because you are trying to do things with the wrong tool. – Temani Afif Aug 14 '19 at 21:38
  • Why i was using canvas was because you just pass x y and stroke multiple shapes is the same possible on svg too using javascript ? – dota2pro Aug 14 '19 at 21:39
  • Yes possible, simply take the time to read more about SVG because you can also place element using coordinates – Temani Afif Aug 14 '19 at 21:40

1 Answers1

2

Try to use image to draw (so snippet not works - but when you edit it - it works)

let xml = new XMLSerializer().serializeToString(circSvg);   // get svg data
let svg64 = btoa(xml);                         // make it base64
let b64Start = 'data:image/svg+xml;base64,';
let image64 = b64Start + svg64;                // prepend a "header"

circImg.src = image64;                         // image source
circImg.onload = x=> {
  can.getContext('2d').drawImage(circImg, 0, 0); // draw
}
svg<br>
<svg id="circSvg" width="100" height="100">
   <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
   Sorry, your browser does not support inline SVG.
</svg> 

<br>canvas<br> <canvas id="can"></canvas>

<img id="circImg" style="display:none">
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345