简体   繁体   English

javascript中SVG到PNG的转换

[英]SVG to PNG Conversion in javascript

I am working on d3.js charts. 我正在研究d3.js图表​​。 I have radar chart that I want to print in PNG format, but when I do conversion it shows nothing and when I save image it saved but totally black or some time gives error 我有要以PNG格式打印的雷达图,但是当我进行转换时,它什么也没显示;当我保存图像时,它保存了,但是全黑或一段时间会出错

I used two methods 1. with simple code that found on google 我使用了两种方法1.使用在Google上找到的简单代码

 var $container = $('#chart');

    content = $container.html().trim();
    canvas = document.getElementById('svg-canvas');

// Draw svg on canvas
    canvg(canvas, content);

// Change img be SVG representation
   var theImage = canvas.toDataURL('image/png');
   $('#svg-img').attr('src', theImage);

In this used Canvg library but it shows nothing and second method is 在这个使用过的Canvg库中,它什么也没显示,第二种方法是

2 2

saveSvgAsPng(document.getElementsByTagName("svg")[0], "diagram.png");

In this saveSvgAsPng library but it gives Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported. 在这个saveSvgAsPng库中,但它给出了对'HTMLCanvasElement'执行'toDataURL'的失败:可能无法导出污染的画布。

I searched but did not understand that what the issue is with the conversion of canvas to PNG is as SVG converts to Canvas but canvas did not convert to PNG 我进行了搜索,但不了解将画布转换为PNG的问题是因为SVG转换为Canvas,但是画布未转换为PNG

If the image you are trying to convert to SVG is comming from another domain, you can't use toDataUrl on it for security reason. 如果您尝试转换为SVG的映像来自另一个域,出于安全原因,您不能在其上使用toDataUrl。

If you have control over the domain serving the image, adding a header 如果您可以控制投放图片的域,请添加标题

Access-Control-Allow-Origin: http://www.domain-where-you-use-your-javascript.com

when serving the image file may fix this issues 提供图片文件时可以解决此问题

(Obviously, replace the domain name by the correct one) (显然,将域名替换为正确的域名)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM