简体   繁体   English

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

[英]Not able to save SVG containing text and image to Canvas

I am drawing the text in SVG on an image based on user input in text box.我正在根据用户在文本框中的输入在图像上绘制 SVG 中的文本。
I want to capture both image and text of SVG to canvas so that我想将 SVG 的图像和文本都捕获到画布上,以便
i can convert it to base 64 string after showing it on canvas.在画布上显示后,我可以将其转换为 base 64 字符串。 I am able to capture the text in canvas but image is not showing.我能够在画布中捕获文本,但图像未显示。

<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>

Have a look at jsfiddle看看 jsfiddle

Here's a link这是一个链接
https://jsfiddle.net/atulpr/0yhpygue/14/ https://jsfiddle.net/atulpr/0yhpygue/14/

This is the same problem as in: Render SVG with external references to Canvas这与以下问题相同: Render SVG with external references to Canvas

You need to embed the image with data URI rather than using external URL.您需要使用数据 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/ https://jsfiddle.net/0yhpygue/15/

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

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