【问题标题】:Creating an image from an svg is not working从 svg 创建图像不起作用
【发布时间】:2021-04-02 07:24:34
【问题描述】:

我一直在尝试从 DataURL 中创建图像(使用 window.Image 类)。此 DataURL 包含一个 svg 标记和一个 foreignObject。但它只是保持完全空。 我也尝试在画布上绘制此图像,但我认为这不是问题,因为我什至无法获得正确外观的图像。

完成的数据URL

data:image/svg+xml;charset=utf8,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%22200%22%20height%3D%22200%22%3E%3CforeignObject%20width%3D%22100%25%22%20height%3D%22100%25%22%3E%3Cdiv%20style%3D%22background-color%3Ared%22%3Etest%3C%2Fdiv%3E%3C%2FforeignObject%3E%3C%2Fsvg%3E

模板化的 SVG 标记

注意:ReactJS 组件 (<Component />) 被解析为字符串。但它不包含任何样式,它只是一个简单的 div,其中包含一些文本。

const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200"><foreignObject width="100%" height="100%">${renderToStaticMarkup(
        <Component />
    )}</foreignObject></svg>`;

模板化的 DataURL

const url = `data:image/svg+xml;charset=utf8,${encodeURIComponent(svg)}`;

加载图片

const image = new window.Image(url);
image.src = url;

图像到画布

const ctx = canvas.getContext("2d");
const image = await loadImage(url) // a simple wrapper function which waits for the image to load that returns a promise
ctx.drawImage(image, 0, 0);

【问题讨论】:

    标签: javascript html css reactjs svg


    【解决方案1】:

    我在使用呼吸锻炼应用程序时遇到了类似的问题。我的应用程序徽标应该显示在主页上,并且在我尝试添加时不会出现。这是我为修复它所做的。

    尝试将 .svg 文件作为模块添加到您的 react-app-env.d 文件中。

    只需将以下行添加到那里的文件列表中,

    declare module '*.svg'
    

    然后像往常一样导入文件,

    import imageName from './filePath'
    

    您应该可以在 img 标签中使用 svg 并且没有问题。

    【讨论】:

      【解决方案2】:

      如果你打开完成的 URL,你可以看到没有红色背景对象,我认为是因为 div 元素没有渲染甚至不存在。

      尝试将 div 元素中的 xmlns 属性设置为http://www.w3.org/1999/xhtml,如下所示:

      data:image/svg+xml;charset=utf8,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%22200%22%20height%3D%22200%22%3E%3CforeignObject%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20x%3D%220%22%20y%3D%220%22%20width%3D%22200%22%20height%3D%22200%22%3E%0A%3Cdiv%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F1999%2Fxhtml%22%20style%3D%22background-color%3A%20red%22%3Etest%3C%2Fdiv%3E%0A%20%20%20%20%3C%2FforeignObject%3E%3C%2Fsvg%3E

      示例:

      <svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">
          <foreignObject x="0" y="0" width="200" height="200">
              <div xmlns="http://www.w3.org/1999/xhtml" style="background-color: red">test</div>
          </foreignObject>
      </svg>

      参考:

      外来对象:https://developer.mozilla.org/en-US/docs/Web/SVG/Element/foreignObject

      【讨论】:

        猜你喜欢
        • 2012-06-21
        • 1970-01-01
        • 2016-05-26
        • 2018-08-31
        • 1970-01-01
        • 2021-10-26
        • 1970-01-01
        • 2011-06-20
        • 1970-01-01
        相关资源
        最近更新 更多