无法将包含文本和图像的SVG保存到画布

Not able to save SVG containing text and image to Canvas

本文关键字:保存 SVG 图像 包含 文本      更新时间:2023-09-26

我根据用户在文本框中的输入,在图像上绘制SVG中的文本
我想将SVG的图像和文本都捕获到画布中,以便
在画布上显示后,我可以将其转换为base64字符串。我能够捕获画布中的文本,但图像不显示。

<body>
  <svg id="svgelem" class="scaling-svg" xmlns="http://www.w3.org/2000/svg">
    <g>
      <image xlink:href="http://i.imgur.com/PWSOy.jpg" x="0" y="0" height="200" width="200" />
      <text x="38%" y="68%" alignment-baseline="middle" text-anchor="middle" font-family="Calibri" font-size="25" id="textbox" fill="black"></text>
    </g>
  </svg>
  <input type="text" name="name" id="name" maxlength="26" />
  <input type="submit" id="drawText" value="Draw It" />
  <div style="clear:both;"></div>
  <br/>
  <canvas id="canvas" style="border:2px solid black;" width="250" height="250">
  </canvas>
</body>

看看jsfiddle

这是一个链接
https://jsfiddle.net/atulpr/0yhpygue/14/

这与中的问题相同:使用Canvas 的外部引用渲染SVG

您需要使用数据URI嵌入图像,而不是使用外部URL。

function embedImage(imageElement) {
  var image = new Image();
  image.setAttribute('crossOrigin', 'anonymous');
  image.src = imageElement.getAttribute('xlink:href');
  image.onload = function() {
    var canvas = document.createElement('canvas');
    canvas.width = image.width;
    canvas.height = image.height;
    canvas.getContext('2d').drawImage(image, 0, 0);
    imageElement.setAttribute('xlink:href', canvas.toDataURL('image/png'));
  }
}

https://jsfiddle.net/0yhpygue/15/