簡體   English   中英

無法將包含文本和圖像的 SVG 保存到 Canvas

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

我正在根據用戶在文本框中的輸入在圖像上繪制 SVG 中的文本。
我想將 SVG 的圖像和文本都捕獲到畫布上,以便
在畫布上顯示后,我可以將其轉換為 base 64 字符串。 我能夠在畫布中捕獲文本,但圖像未顯示。

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

這與以下問題相同: Render SVG with external references to Canvas

您需要使用數據 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/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM