javascript - 如何将 <image> 元素添加到 SVG DOM

标签 javascript jquery svg raphael

我有一个带有 jpg 图像的网页,用户在使用 Raphael 的基础上绘制了 SVG 涂鸦。

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

当用户单击保存时,我想将该背景图像作为元素添加到生成的 SVG DOM 中,然后使用 canvg 将 SVG 写入 Canvas 元素。最后,我使用 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);

关于javascript - 如何将 <image> 元素添加到 SVG DOM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10859257/

相关文章:

javascript - D3 和​​ Leaflet - svg 圆圈不显示

angular - ionic 图标不显示

javascript - 在 PDF 文件上打印生成的 QR 码

javascript - 如何使用 jest 模拟 react-router-dom 的 BrowserRouter

javascript - 用于计算金额的计数器

javascript - 进度事件监听器一次加载一个缩略图

javascript - jQuery 自动将 div 定位在屏幕中心

javascript - 在 jQuery 中使用 BIND 或 ON 函数的最佳实践

javascript - 如何在没有 JQuery 的情况下从 Javascript 发出 JSONP 请求?

javascript - 使用 jquery 将页面中所有文本框的数字向下舍入到最接近的整数?