简体   繁体   English

原生SVG到Canvas或SVG到图像的转换

[英]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? 我读到这篇文章: 有没有一种方法可以将SVG文件转换为HTML5的canvas兼容命令? 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. SVG文档在浏览器将其呈现在屏幕上之后以像素形式显示在屏幕上,将这些像素作为图像提供给用户将是最简单的任务。

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

This is now possible native. 现在这是本地的。


From MDN, 从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. 只需将svg字符串替换为您自己的svg。


PS. PS。 The perf seems to be much much better by rendering on canvas vs rendering as normal DOM! 与在普通DOM上进行渲染相比,在画布上进行渲染似乎可以使性能更好! Perf for render to canvas seems consistently around 50x faster than perf for normal dom (tested on Chrome, Safari, and mobile Chrome). 用于渲染到画布的性能似乎始终比普通dom (在Chrome,Safari和移动Chrome上测试)的性能 50倍

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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