r3plica
r3plica

Reputation: 13377

AngularJS download SVG as JPG

I am trying to create a directive that will convert an SVG into a JPG/PNG. I found this site:

http://bl.ocks.org/mbostock/6466603

So I was trying to do the same with this:

.directive('export', function () {
    return {
        restrict: 'A',
        scope: {
            target: '@export'
        },
        link: function (scope, element) {

            // Bind to the onclick event of our button
            element.bind('click', function (e) {

                // Prevent the default action
                e.preventDefault();

                var target = document.getElementById(scope.target),
                    canvas = document.querySelector('canvas'),
                    context = canvas.getContext('2d');

                console.log(target);

                if (target) {

                    var preview = target.getElementsByTagName('svg');

                    console.log(preview);

                    var img = new Image;

                    img.src = preview[0];
                    img.onload = function () {

                        console.log('loaded');

                    };
                }
            });
        }
    };
});

The problem is the img.src. I am not sure if I am setting it right, in the example on the site above it uses a location rather than the actual svg file. Does anyone know how I can get this to work?

Upvotes: 2

Views: 1268

Answers (1)

Drew Gaynor
Drew Gaynor

Reputation: 8472

A URL can actually be created from the SVG element using createObjectURL. For more information on this technique see the more general topic of Drawing DOM objects into a canvas on MDN.

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var data = document.getElementById('container').innerHTML;
var DOMURL = window.URL || window.webkitURL || window;
var img = new Image();
var svg = new Blob([data], {type: 'image/svg+xml;charset=utf-8'});
var url = DOMURL.createObjectURL(svg);

img.onload = function () {
  ctx.drawImage(img, 0, 0);
  DOMURL.revokeObjectURL(url);
}

img.src = url;
canvas {
  border: 1px dashed red;
}
<div id="container">
  <svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" id="svg">
    <rect width="50" height="50"></rect>
  </svg>
</div>

<canvas width="200" height="200" id="canvas"></canvas>

Upvotes: 1

Related Questions