Ioannis Anifantakis
Ioannis Anifantakis

Reputation: 35

Export external SVG file painted with Javascript to PNG image

I am using an svg map from an external file. I insert it to my html code using the "object" tag.

<object id="mymap" data="map.svg" width="884" height="760" type="image/svg+xml" ></object>

In javascript I paint paths of the svg map with some given colors. For example:

<script>
var path1 = document.getElementById('mymap').getSVGDocument().getElementById('path1');
path1.style.fill='#f00';

var path2 = document.getElementById('mymap').getSVGDocument().getElementById('path2');
path2.style.fill='#0f0';
</script>

How can I export the resulted coloured map as a PNG image?

--UPDATE-- : The question has been answered, and the LiveExample now includes the solution for future reference. You can view the source and get the solution. The example draws a map and saves drawn map in a canvas that you can then save as file

Upvotes: 2

Views: 1627

Answers (2)

Ioannis Anifantakis
Ioannis Anifantakis

Reputation: 35

Solution is the following: Based on my accepted solution I include the full javascript that manages all steps

Create a canvas

<canvas id="canvas" style="border:1px solid black;" width="884" height="760"></canvas>

Draw into that canvas the image from the painted svg

function drawCanvas(){
    // create a canvas and context
    var canvas = document.getElementById('canvas');
    var ctx = canvas.getContext('2d');


    // define svgdocument and make blob containing its data
    var svgDoc = document.getElementById('mymap').getSVGDocument();
    var svg = new Blob([svgDoc.lastChild.outerHTML], {type: 'image/svg+xml;charset=utf-8'});


    // create a new image
    var DOMURL = window.URL || window.webkitURL || window;
    var url = DOMURL.createObjectURL(svg); 
    var img = new Image(); 
    img.onload = function(){ 
        ctx.drawImage(img,0,0,884,760); 
        DOMURL.revokeObjectURL(url);
    };
    img.src = url;
}

Upvotes: 1

ChinKang
ChinKang

Reputation: 4342

What about drawing the svg to the canvas, and then use the .toDataURL to get as PNG image?

--Update-- For a quick test, i run the below in the console from your live demo:

var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var svgDoc = document.getElementById('mymap').getSVGDocument();
var svg = new Blob([svgDoc.lastChild.outerHTML], {type: 'image/svg+xml;charset=utf-8'});
var img = new Image(); 
img.onload = function(){ ctx.drawImage(img,0,0); };
img.src = url

you should see the url, which has the image draw, at this time just call the .toDataURL you should get the base64 image data

Upvotes: 0

Related Questions