如何将<图像>元素添加到 SVG DOM

How can I add an <image> element to the SVG DOM

本文关键字:添加 DOM 元素 SVG 图像      更新时间:2023-09-26

我有一个带有jpg图像的网页,用户在使用Raphael的顶部绘制SVG涂鸦。

我想允许用户在完成后保存此合并的光栅化版本(我将自己使用 SVG 版本做其他事情)

当用户单击保存时,我想将该背景图像作为元素添加到生成的 SVG DOM 中,然后使用 canvg 将 SVG 写入画布元素。最后,我使用 toDataUrl() 方法将其转换为 jpg。

我无法让中间位工作 — 将图像添加到 DOM 的最佳方法是什么?当我使用以下代码时,我收到一个javascript错误,说appendChild()不是一个函数。

想知道它是否与我如何使用 .html() 方法获取 SVG 有关——也许返回的内容没有被解释为真正的 SVG 文档?

任何帮助非常感谢。

    function saveImage(){
        var img = document.getElementById('canvas').toDataURL("image/png");
        window.open(img,'Download');
    }
    $('#save').click(function(){
        var svg = $('#editor').html();
        // Create new SVG Image element.  Must also be careful with the namespaces.
        var svgimg = document.createElementNS("http://www.w3.org/2000/svg", "image");
        svgimg.setAttributeNS("http://www.w3.org/1999/xlink", 'xlink:href', "myimage.jpg");

        // Append image to SVG
        svg.appendChild(svgimg);
        canvg('canvas', svg, {renderCallback: saveImage(), ignoreMouse: true, ignoreAnimation: true, ignoreDimensions: true});
    });

这里有一种方法可以做到这一点:

var svgimg = document.createElementNS('http://www.w3.org/2000/svg','image');
svgimg.setAttributeNS(null,'height','200');
svgimg.setAttributeNS(null,'width','200');
svgimg.setAttributeNS('http://www.w3.org/1999/xlink','href', 'myimage.jpg');
svgimg.setAttributeNS(null,'x','10');
svgimg.setAttributeNS(null,'y','10');
svgimg.setAttributeNS(null, 'visibility', 'visible');
$('svg').append(svgimg);