Get SVG from canvas element and save it

后端 未结 2 910
再見小時候
再見小時候 2020-12-23 17:24

Currently I\'m creating a small application for a friend, who´s starting his PhD and needs to build some network graphs. So far everything works fine using the a Force Direc

2条回答
  •  无人及你
    2020-12-23 17:58

    If you want to preserve it as a vector graphic instead of as a raster, you can try one of the libraries that translate the canvas API operations to svg.

    For SVGKit:

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

    Full running example of the above.

    For canvas-svg:

    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());
    

    Full running example of the above.

    For generating svg instead:

    Another option is of course to make the graph as an svg in the first place, d3.js is a javascript library that makes it easy to do this, see e.g this example of a force directed graph.

提交回复
热议问题