简体   繁体   English

将 HTML5 Canvas 绘图应用程序另存为 SVG 文件

[英]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? 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我? This is the html code for the save png image button:这是保存 png 图像按钮的 html 代码:

<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:和 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.请帮助。我不允许使用其他 js 库。

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). 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.既然这是一个绘图工具,您可能会使用对象和/或其他数据结构维护编辑器的 state。 With that assumption, the entire image is already represented in a structured manner.有了这个假设,整个图像已经以结构化的方式表示。 And this structure could be used for generating an SVG image.该结构可用于生成 SVG 图像。 Example: a circle is drawn on the canvas with a color, size and position: {type: "circle", color: "red", x: 30, y: 56, r: 5} .示例:在 canvas 上画了一个圆,颜色、大小和 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.这个 object 在 canvas 上绘制为圆弧,但同时也可以变成 SVG <circle>元素。

There are probably more libraries that can handle this for you.可能有更多的库可以为您处理这个问题。 fabricjs could be an example. fabricjs 可能就是一个例子。 Here I link to the toSVG() function: JSDoc: Class: Canvas .这里我链接到toSVG() function: JSDoc: Class: Canvas

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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