目前,我正在为一个朋友创建一个小应用程序,他正在启动他的PhD,需要构建一些网络图。到目前为止,使用a Force Directed图一切正常。可以移动图形节点来设置布局的样式。
我想不通的是:
SVG »如何从画布中提取数据并将其保存到
文件«。
我尝试过的:
我已经尝试过从控制台访问图像数据
var app.canvas = document.getElementById( 'graph-canvas' )
.getContext( '2d' )
.getImageData( 0, 0, 200, 200 );
并得到了一个(object) ImageData
作为回报。现在我可以用app.canvas.data
访问显示的↑画布数据了。(当我尝试查找这些值时,浏览器开始挂起,并询问是否应该停止脚本- Chrome & FF latest)。
从这里开始,我如何通过单击按钮来绘制并保存SVG?
编辑:
到目前为止,我已经了解了如何绘制SVG并向其中添加image/png
元素。无论如何,它没有显示出来。
// Add the test SVG el:
var svg = document.createElementNS( "http://www.w3.org/2000/svg", "svg" );
svg.setAttribute( 'style', 'border: 1px solid black;' )
.setAttribute( 'width', '600' )
.setAttribute( 'height', '400' )
.setAttributeNS(
'http://www.w3.org/2000/xmlns/',
'xmlns:xlink',
'http://www.w3.org/1999/xlink'
);
// Call
importCanvas( document.getElementById( 'infovis-canvas' ), svg );
// Function: Add data to SVG
function importCanvas( sourceCanvas, targetSVG )
{
// get base64 encoded png data url from Canvas
var img_dataurl = sourceCanvas.toDataURL( "image/png" );
var svg_img = document.createElementNS(
"http://www.w3.org/2000/svg",
"image"
);
svg_img.setAttributeNS(
'http://www.w3.org/1999/xlink',
'xlink:href',
img_dataurl
);
jQuery( targetSVG.appendChild( svg_img ) )
.appendTo( '#graph-container' );
console.log( 'done' ); // Log & confirm
}
最后..。
// ...resulting SVG element containing the image element
<svg style="border: 1px solid black;" width="600" height="400" xlink="http://www.w3.org/1999/xlink"><image href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABQAAA(...)
该UI可与jQuery UI、jQuery和库配合使用,因此这些都是可用的。
发布于 2012-04-23 14:37:40
如果希望将其保存为矢量图形而不是栅格,可以尝试将canvas API操作转换为svg的库之一。
适用于 的
var svgkitContext = new SVGCanvas(150,150);
function draw(ctx) {
// ... normal canvas drawing commands go here ...
}
// draw to SVGKit canvas (svg) instead of canvasElement.getContext("2d")
draw(svgkitContext);
上面的完全运行的example。
适用于 的
var canvasSVGContext = new CanvasSVG.Deferred();
canvasSVGContext.wrapCanvas(document.querySelector("canvas"));
var canvasContext = document.querySelector("canvas").getContext("2d");
function draw(ctx) {
// ... normal canvas drawing commands go here ...
}
// draw to html5 canvas and record as svg at the same time
draw(canvasContext);
// append the svg result
var svg = document.appendChild(canvasContext.getSVG());
上面的完全运行的example。
用于生成svg的:
另一种选择当然是首先将图形制作为svg,d3.js是一个javascript库,可以很容易地做到这一点,参见例如力定向图形的this example。
发布于 2012-04-23 23:42:50
如果你被限制在ImageData
上,那你就不走运了,因为那只是一个像素阵列(参见reference)。您不能从那里获得有意义的SVG图像。您可能会生成一个.png
representation...but,它是一个没有交互的静态图像。
如果您要将canvas导出为SVG,那么如何绘制canvas是很重要的。最好的方法是使用维护canvas scene graph的库。
Fabric.js似乎是个不错的选择。您可以使用canvas进行绘制,然后调用canvas.toSVG()
并获得您的svg图像。
https://stackoverflow.com/questions/10273516
复制相似问题