How to convert canvas to SVG with embedded image base64 in fabricjs

匿名 (未验证) 提交于 2019-12-03 08:48:34

问题:

I have fabricjs canvas with image, which I loaded by fabric.Image.fromURL() method.

I need export it to SVG, but I want to export image as embedded source in base64, not as a link.

How can I do it? Is it any way to load image as a source not as a link?

Example code:

Loading image:

fabric.Image.fromURL('./assets/people.jpg', function (image) {     image.set({         left: 10,         top: 30     });     canvas.add(image); }; 

Exporting to SVG:

canvas.toSVG(); 

In exported SVG I have:

<image xlink:href="http://localhost:8383/app/assets/people.png" /> 

But I want it in base64 like:

<image xlink:href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAe8AAAKuCAYAAACIZZSZAAAAAXNSR0IArs4c6QAAAARnQU1BAACx(...)" /> 

回答1:

There is no option but you can easily achieve it like this: Image has a method that is called 'getSvgSrc';

override it like this:

fabric.Image.prototype.getSvgSrc = function() {   return this.toDataURLforSVG(); };  fabric.Image.prototype.toDataURLforSVG = function(options) {   var el = fabric.util.createCanvasElement();   el.width = this._element.naturalWidth;   el.height = this._element.naturalHeight;   el.getContext("2d").drawImage(this._element, 0, 0);   var data = el.toDataURL(options);   return data; }; 

In this way you should be able to obtain an integrated image for the svg.



回答2:

you can use the toSVG method :

rasterizeSVG () {     let w = window.open('')     w.document.write(this.canvas.toSVG())     return 'data:image/svg+xml;utf8,' + encodeURIComponent(this.canvas.toSVG())   } 

or :

rasterize() {   if (!fabric.Canvas.supports('toDataURL')) {     alert('This browser doesn\'t provide means to serialize canvas to an image');   }   else {     var image = new Image();     image.src = this.canvas.toDataURL('png')     var w = window.open("");     w.document.write(image.outerHTML);   } } 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!