Timo Kähkönen
Timo Kähkönen

Reputation: 12210

Native SVG to Canvas or SVG to image conversion

I read this:Is there a way to convert SVG files to HTML5's canvas compatible commands? and tried google.

Is there a native (cross-browser) way? SVG document is on screen as pixels after browser has rendered it on screen and it would be the simplest task to give those pixels as an image to user.

Upvotes: 1

Views: 266

Answers (2)

resgh
resgh

Reputation: 984

This is now possible native.


From MDN,

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

var data = '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">' +
           '<foreignObject width="100%" height="100%">' +
           '<div xmlns="http://www.w3.org/1999/xhtml" style="font-size:40px">' +
             '<em>I</em> like ' + 
             '<span style="color:white; text-shadow:0 0 2px blue;">' +
             'cheese</span>' +
           '</div>' +
           '</foreignObject>' +
           '</svg>';

var DOMURL = window.URL || window.webkitURL || window;

var img = new Image();
var svg = new Blob([data], {type: 'image/svg+xml'});
var url = DOMURL.createObjectURL(svg);

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

img.src = url;

Just replace the svg string with your own svg.


PS. The perf seems to be much much better by rendering on canvas vs rendering as normal DOM! Perf for render to canvas seems consistently around 50x faster than perf for normal dom (tested on Chrome, Safari, and mobile Chrome).

Upvotes: 1

dbugger
dbugger

Reputation: 16399

Paperjs is a nice little wrapper library around canvas, and it has an SVG import function.

Upvotes: 1

Related Questions