SVG image is not rendering with proper font in image tag and canvas

<html>
<head>
<link href='https://fonts.googleapis.com/css?family=DM+Sans' rel='stylesheet'>

<style>

body {
    font-family: 'DM Sans';font-size: 22px;
}
</style>
</head>
<body>
<h1>DM Sans applied words are below</h1>

<p>Contract Sum<br>Adjusted Contract Sum<br>Difference<br>Spent To Date<br>Left To Spend<br>Forecast CSum Approved VO's<br>orecast CSum Open VO's</p>

<img id="svg" src="svg.svg" alt="The Scream">

<p>Canvas:</p>

<canvas id="myCanvas" width="700" height="600" style="border:1px solid grey;"></canvas>

<script>
window.onload = function() {
  const canvas = document.getElementById("myCanvas");
  const ctx = canvas.getContext("2d");
  const img = document.getElementById("svg");
   ctx.font = "30px 'DM Sans'";
   ctx.fillText("Contract Sum",20,20);
  ctx.drawImage(img, 100, 100);
};
</script>

</body>
</html>

SVG image with DM SANS font is not rendering properly in image source and canvas.

1 Like

I don’t really know anything about this and is more of a JS question so I’ll move the thread to JS.

I did find some info from below that might be pertinent and it seems you may need this type of set up.

e.g.

window.onload = function () {
  const canvas = document.getElementById("myCanvas");
  const img = document.getElementById("svg");
  const fontFile = new FontFace(
    "DM Sans",
    "url(https://fonts.gstatic.com/s/dmsans/v14/rP2tp2ywxg089UriI5-g4vlH9VoD8CmcqZG40F9JadbnoEwAopxRSW32RmYJp8I5.woff2)"
  );
  document.fonts.add(fontFile);

  fontFile.load().then(
    () => {
      const ctx = canvas.getContext("2d");

      ctx.drawImage(img, 100, 100);
      ctx.font = '30px "DM Sans"';
      ctx.fillText("Contract Sum", 20, 20);
    },
    (err) => {
      console.error(err);
    }
  );
};

However you may need to wait for someone more knowledgeable to come along :wink:

1 Like

I find the text in the <canvas> element appears as expected; here with a more distictive font:

I may be wrong but I would not expect to be able to change the font within an SVG that is rendered as an <img> element.

1 Like

Yes that does appear to be working. I must have copied incorrectly when I first tested :frowning:

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.