I'm struggling with a piece of code that creates an SVG and then displays it on a canvas. Here is the Jsbin Link for reference: https://jsbin.com/lehajubihu/1/edit?html,output
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>JS Bin</title>
<style>
#imgNode {
border: "10px dotted black";
}
</style>
</head>
<img id="imgNode" style="border: 1px dotted black"></img>
<body>
<script>
const { body } = document;
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
const tempImg = document.createElement("img");
tempImg.addEventListener("load", onTempImageLoad);
tempImg.src =
"data:image/svg+xml;base64," +
btoa(
'<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%"><foreignObject width="100%" height="100%"><div xmlns="http://www.w3.org/1999/xhtml"><style>em{color:red;}</style><em>I</em> lick <span>cheese</span></div></foreignObject></svg>'
);
const targetImg = document.querySelector("#imgNode")
function onTempImageLoad(e) {
ctx.drawImage(e.target, 0, 0);
targetImg.src = canvas.toDataURL();
}
</script>
</body>
</html>
Although the code runs smoothly, I noticed that the width and height of the rendered image are fixed and not dynamic. This results in extra space around the HTML content as visible in this image: https://i.sstatic.net/zekG1.png
My question is, how can I adjust the width and height to make the image/canvas render only the HTML content without any additional space?