简体   繁体   中英

How To Make Canvas Dynamically Render To Size Of Image?

I have this snippet of code that makes an SVG and draws it to a canvas.

Jsbin Link: 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," +
        encodeURIComponent(
          '<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>

The code does work but the width and height is not dynamic. From the image, we can see that the size is very big compared to the size of the actual HTML as shown below

在此处输入图像描述

How do I make the image/canvas render only the HTML and no extra space?

In your image rendering function onTempImageLoad(e) you can add this:

function onTempImageLoad(e) {
        canvas.width = tempImg.width;
        canvas.height = tempImg.height;
        
        ctx.drawImage(e.target, 0, 0);
        targetImg.src = canvas.toDataURL();
      }

But you need to check your svg because it's the one that contains extra spaces. It seems to be in 300x150, you can do some tests by setting the size of the svg in pixels by replace width="100%" and height="100%".

tempImg.src =
        "data:image/svg+xml," +
        encodeURIComponent(
          '<svg xmlns="http://www.w3.org/2000/svg" width="100px" height="50px"><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>'
        );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM