简体   繁体   中英

Save HTML5 Canvas Drawing App as a SVG file

I'm doing a canvas drawing app and i want to be able to export the image as a svg file .I already did the function to save the image as a png file but i have some troubles with the svg part.Can you please help me? This is the html code for the save png image button:

<div class="wrapper">

    <div class="toolbar">
        <a href="#" id="save" onclick="SaveImage()">
        <img src="save.png"></a>
    </div>

<canvas id="my-canvas" width="800" height="500"></canvas>

<div id="toolbar2">
    <a id="img-file" download="image.png">
    <button onClick="download()" type="button" class="button">Save as PNG</button></a>
</div> 

And the JS:

function SaveImage(){
    var imageFile = document.getElementById("img-file");
    imageFile.setAttribute('download', 'image.png');
    imageFile.setAttribute('href', canvas.toDataURL());
}

Please help.I`m not allowed to use other js libraries.

You cannot convert the bitmap image of the canvas directly to SVG (except if the bitmap image like the PNG that you have tried to export is the source of a <image> element in your SVG -- but I guess that that is not the idea).

Now that this is a drawing tool, you probably maintain the state of the editor with objects and/or another data structure. With that assumption, the entire image is already represented in a structured manner. And this structure could be used for generating an SVG image. Example: a circle is drawn on the canvas with a color, size and position: {type: "circle", color: "red", x: 30, y: 56, r: 5} . This object is drawn as an arc on the canvas, but at the same time it can also be turned into a SVG <circle> element.

There are probably more libraries that can handle this for you. fabricjs could be an example. Here I link to the toSVG() function: JSDoc: Class: Canvas .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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