简体   繁体   中英

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.

Paperjs是一个很好的围绕画布的小包装器库,它具有SVG导入功能

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).

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