簡體   English   中英

RaphaelJS 到 SVG 到

[英]RaphaelJS to SVG to

我試圖讓用戶將 SVG 圖形下載為 PNG。 您可以通過JSFIDDLE 獲取代碼

SVG 到 CANVAS 部分不工作。

已經添加了 canvg 和 Mozillas 的代碼,它們都不起作用。 還添加了 Canvas2Image 如果 canvas 有元素,它應該可以工作。

感謝開發 canvg 的 gabelerner 幫助我修復它

  1. 基於問題另存為 png 由 Raphael JS 在 canvas 中生成的 SVG ,去除 svg 中標簽之間的所有空格
  2. 基於問題另存為 png 由 Raphael JS 在 canvas 圖像的 href 中生成的 SVG更改為 xlink:href
  3. 基於 gabelerner,將 xmlns:xlink="http://www.w3.org/1999/xlink" 添加到 svg xlmns
  4. 基於 gabelerner,圖像必須在同一個域下 - 沒有交叉邊
  5. 基於 gabelerner,Canvas2Image 不能在框架內工作,這意味着沒有 FIDDLE(因此我刪除了 FIDDLE 部分以使其清楚)

這是您可能想要的示例 SVG 和 JS 部分

var svg_XML_NoSpace = '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="1024" height="768"><desc>Created with Raphaël</desc><defs></defs><image x="0" y="0" width="1024" height="768" preserveaspectratio="none" xlink:href="http://<mydomain>/<myfolder>/<myfile>"></image><path fill="none" stroke="#ff0000" d="M414,114L722,114" style="stroke-width: 3px;" stroke-width="3"></path></svg>'; //based on gabelerner

//add canvas into body        
var canvasID = "myCanvas";
var canvas = document.createElement('canvas');
canvas.id = canvasID;
document.body.appendChild(canvas);

//convert svg to canvas
canvg(document.getElementById(canvasID), svg_XML_NoSpace, { 
    ignoreMouse: true, ignoreAnimation: true, 
    renderCallback: function () {
         //save canvas as image
         Canvas2Image.saveAsPNG(document.getElementById(canvasID));  
         }
} );

Try converting SVG to canvas with fabric.js (here's a demo , in which svg is converted to canvas in real time, when you click on a button in sidebar).

Fabric 不支持所有 SVG 功能,但它應該適用於簡單的情況。

這是使用loadSVGFromURL的示例。

1)你需要有 <canvas> 元素:

<canvas id="my-canvas"></canvas>

2)從canvas中初始化fabric.Element

var canvas = new fabric.Element('my-canvas');

3) 通過 XHR 獲取 SVG:

canvas.loadSVGFromURL('path_to_your_shape.svg', function(objects, options) {

  // `objects` is now an array of fabric objects representing 
  // svg shapes from the document
  // if it's one shape, we'll just work with that
  // if it's more than one — we'll create a unified group out of it, 
  // using `fabric.PathGroup`

  var loadedObject = objects.length > 1 
    ? new fabric.PathGroup(objects, options) 
    : objects[0];

  // we can now change object's properties like left, top, angle, opacity, etc.
  // this is not necessary, of course

  loadedObject.set({
    left: 123,
    top: 321,
    angle: 55,
    opacity: 0.3
  });

  // and add it to canvas

  canvas.add(loadedObject);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM