繁体   English   中英

如何使 Canvas 动态渲染到图像大小?

[英]How To Make Canvas Dynamically Render To Size Of Image?

我有这段代码可以生成 SVG 并将其绘制到 canvas。

jsbin链接: 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>

该代码确实有效,但宽度和高度不是动态的。 从图像中我们可以看到,与实际 HTML 的大小相比,大小非常大,如下所示

在此处输入图像描述

如何使图像/画布仅渲染 HTML 而没有额外空间?

在你的图像渲染 function onTempImageLoad(e) 你可以添加这个:

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

但是您需要检查您的 svg,因为它包含额外的空格。 它似乎是 300x150,您可以通过替换 width="100%" 和 height="100%" 来设置 svg 的像素大小来做一些测试。

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>'
        );

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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