【问题标题】:SVG with pattern and image element conversion to PNG Image failed带有图案和图像元素的 SVG 转换为 PNG 图像失败
【发布时间】:2013-05-10 22:22:55
【问题描述】:

我正在尝试将使用 Raphael.js 生成的 svg 转换为 PNG 图像。好吧,当 svg 没有图案和图像组件时,我将 svg 转换为图像。然后当我将这两个组件添加到 SVG 中时再次出现问题并且转换失败。完整的小提琴是 here。即使我保存生成的 svg 并在浏览器中打开而不转换为图像,也不会渲染图像和图案。

sn-p的代码是:

var r = Raphael(document.getElementById("cus"), 390, 253);
    r.setViewBox(-5, -2, 228, 306);
    for (var outline in doorMatOutline) {
        var path = r.path(doorMatOutline[outline].path);
        //path.attr({fill: 'url('+patternuri+')'}); //adding pattern        
    }
    //adding image
    var img = r.image(imageuri, 5 ,10 ,100 ,100);

    var svg = $('#cus').html().replace(/>\s+/g, ">").replace(/\s+</g, "<");

    canvg('cvs', svg, {
        ignoreMouse: true,
        ignoreAnimation: true
    });

    var canvas = document.getElementById('cvs');
    var img = canvas.toDataURL("image/png");

    $("#resImg").attr('src', img);
    $("#cus").hide();

【问题讨论】:

    标签: jquery svg raphael


    【解决方案1】:

    我已经在http://jsfiddle.net/fktGL/1/ 解决了这个问题,首先我必须将 svg 属性从

    xmlns="http://www.w3.org/2000/svg"

    xmlns:xlink="http://www.w3.org/1999/xlink"
    

    因为 svg 没有在 W3C 验证服务上进行验证,而 here 是一个解释需要更改的 stackoverflow。

    然后我不得不添加一些超时以允许 SVG 正确呈现。我知道这是因为图像已在 SVG 和画布中绘制,但两者都需要一些时间来渲染图像。我的解决方案在较慢的设备上无法完美运行(增加超时会有所帮助),但我不知道另一种解决方法(欢迎任何 cmets/改进)。

    这是最后的片段

    var r = Raphael(document.getElementById("cus"), 390, 253);
    r.setViewBox(-5, -2, 228, 306);
    for (var outline in doorMatOutline) {
        var path = r.path(doorMatOutline[outline].path);
        path.attr({
            fill: 'url(' + patternuri + ')'
        });
    }
    
    $('#cus svg').removeAttr('xmlns');
    
    // If not IE
    if(/*@cc_on!@*/false){
        $('#cus svg').attr('xmlns:xlink',"http://www.w3.org/1999/xlink");
    }
    
    
    // First timeout needed to render svg (I think)
    setTimeout(function(){ 
        var svg = $('#cus').html();
        window.svg = svg;
        canvg(document.getElementById('cvs'), svg);
        // annother delay required after canvg
        setTimeout(function(){
            var canvas = document.getElementById('cvs'),
                img = canvas.toDataURL("image/png");
            $("#resImg").attr('src', img);
            //$("#cus").hide();
            console.log("ending... ");
        },100)
    },100);
    

    【讨论】:

    • 图像看起来像 png 中的平铺。
    • 它适用于 Firefox 和 chrome。 IE 中存在与canvg 脚本相关的错误。我会看看,但不确定是否有一个简单的解决方案。
    • 更新了在 IE 中工作的答案,希望它对你有用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-13
    • 2022-07-05
    • 1970-01-01
    • 1970-01-01
    • 2014-02-23
    • 1970-01-01
    • 2012-09-17
    相关资源
    最近更新 更多