【问题标题】:How can I add an <image> element to the SVG DOM如何将 <image> 元素添加到 SVG DOM
【发布时间】:2012-06-07 05:23:39
【问题描述】:

我有一个带有 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});

    });

【问题讨论】:

    标签: javascript jquery svg raphael


    【解决方案1】:

    这是一种方法:

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

    【讨论】:

    • 不起作用,附加了图像标签但没有完成网络调用,中途我这里没有使用jquery,而是原生元素
    猜你喜欢
    • 2013-05-05
    • 2019-03-26
    • 1970-01-01
    • 2019-05-24
    • 2018-07-15
    • 2016-05-17
    • 2018-01-21
    • 1970-01-01
    相关资源
    最近更新 更多