我正在根据文本框中的用户输入在图像上绘制 SVG 文本。
我想将 SVG 的图像和文本捕获到 Canvas 上,以便
在 Canvas 上显示后,我可以将其转换为 Base 64 字符串。我能够
在 Canvas 中捕获文本,但图像未显示。
<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
最佳答案
这与以下问题相同: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'));
}
}
关于javascript - 无法将包含文本和图像的 SVG 保存到 Canvas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37195924/