Search code examples
javascripthtmlsvgcanvassymbols

SVG to Canvas with HTML Symbol


<svg id="s1" xmlns="http://www.w3.org/2000/svg" width="400" height="400">
<rect width="100%" height="100%" fill="none" stroke="black" />
<foreignObject x="0" y="0" width="100%" height="100%">
<p style="font-size:200px;text-align:center;">&#128512;</p>
</foreignObject>
</svg>
<canvas id="c1" width="400" height="400"></canvas>
<script>
let img = new Image();
let b64 = "data:image/svg+xml;base64,";
let xml = new XMLSerializer().serializeToString(s1);
b64 += btoa(xml);//InvalidCharacterError: String contains an invalid character
let ctx = c1.getContext("2d");
img.onload = function(){
   ctx.drawImage(img, 0, 0);
};
img.src = b64;
</script>

enter image description here Hello, Do you have any idea how to convert svg with a symbol like "😀" to canvas here?

Console: InvalidCharacterError: String contains an invalid character

It works with a normal text like "hello" for example.

Thanks.


Solution

  • btoa and atob only support acscii strings but we can work around that by encoding and decoding the string

    let img = new Image();
    let b64 = "data:image/svg+xml;base64,";
    let s1 = document.getElementById("s1");
    let xml = new XMLSerializer().serializeToString(s1);
    b64 += btoa(unescape(encodeURIComponent(xml)));
    let ctx = c1.getContext("2d");
    img.onload = function(){
       ctx.drawImage(img, 0, 0);
    };
    img.src = b64;
    <svg id="s1" xmlns="http://www.w3.org/2000/svg" width="400" height="400">
    <rect width="100%" height="100%" fill="none" stroke="black" />
    <foreignObject x="0" y="0" width="100%" height="100%">
    <p style="font-size:200px;text-align:center;">&#128512;</p>
    </foreignObject>
    </svg>
    <canvas id="c1" width="400" height="400"></canvas>