简体   繁体   中英

SVG to PNG Conversion in javascript

I am working on d3.js charts. 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

I used two methods 1. with simple code that found on 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

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.

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

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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