经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 软件/图像 » SVG » 查看文章
前端使用 Konva 实现可视化设计器(9)- 另存为SVG
来源:cnblogs  作者:xachary  时间:2024/5/8 9:12:12  对本文有异议

请大家动动小手,给我一个免费的 Star 吧~

大家如果发现了 Bug,欢迎来提 Issue 哟~

github源码

gitee源码

示例地址

另存为SVG

这一章增强了另存为的能力,实现“另存为SVG”,大概是全网唯一的实例分享了吧。

灵感来源:react-konva-custom-context-canvas-for-use-with-canvas2svg

大神提到了 canvas2svg,表达了可以通过创建一个 canvas2svg 的实例,作为 CanvasRenderingContext2D 替换了 Konva 原有 canvas 的 CanvasRenderingContext2D,并使其 layer 重绘,canvas2svg 的实例借此监听 canvas 的动作,转换成 Svg 动作,最终生成 svg 内容。

不过,大神的例子,并没有说明如何处理并导出图片节点

通过测试大神的例子,并观察导出的 svg xml 特点,以下是基本实现思路和注意事项:
1、必须通过替换 layer 的 context 实现,通过 stage 是无效的。
2、导出的 svg xml,图片节点将以 svg 的 image 节点存在。
3、svg 图片素材节点的 xlink:href 以 blob: 链接定义。
4、其它图片素材节点的 xlink:href 是以一般路径链接定义。
5、通过正则表达式提取图片素材节点链接。
6、fetch svg 图片素材节点链接,获得 svg xml 文本。
7、fetch 其它图片素材节点,获得 blob 后,转换为 base64 链接。
8、替换 canvas2svg 导出的 svg xml 内的 svg 图片素材节点为内嵌 svg 节点(xml)。
9、替换 canvas2svg 导出的 svg xml 内的其它图片素材节点的 xlink:href 为 base64 链接
10、导出替换完成的 svg xml。

关键逻辑

功能入口

主要是 canvas2svg 的使用,获得原始的 rawSvg xml 内容:

  1. // 获取Svg
  2. async getSvg() {
  3. // 获取可视节点和 layer
  4. const copy = this.getView()
  5. // 获取 main layer
  6. const main = copy.children[0] as Konva.Layer
  7. // 获取 layer 的 canvas context
  8. const ctx = main.canvas.context._context
  9. if (ctx) {
  10. // 创建 canvas2svg
  11. const c2s = new C2S({ ctx, ...main.size() })
  12. // 替换 layer 的 canvas context
  13. main.canvas.context._context = c2s
  14. // 重绘
  15. main.draw()
  16. // 获得 svg
  17. const rawSvg = c2s.getSerializedSvg()
  18. // 替换 image 链接
  19. const svg = await this.parseImage(rawSvg)
  20. // 输出 svg
  21. return svg
  22. }
  23. return Promise.resolve(
  24. `<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="720"></svg>`
  25. )
  26. }

替换 image 链接方法

根据 xlink:href 链接的特点,通过正则表达式提取,用于后续处理:

  1. // 替换 image 链接
  2. parseImage(xml: string): Promise<string> {
  3. return new Promise((resolve) => {
  4. // 找出 blob:http 图片链接(目前发现只有 svg 是)
  5. const svgs = xml.match(/(?<=xlink:href=")blob:https?:\/\/[^"]+(?=")/g) ?? []
  6. // 其他图片转为 base64
  7. const imgs = xml.match(/(?<=xlink:href=")(?<!blob:)[^"]+(?=")/g) ?? []
  8. Promise.all([this.parseSvgImage(svgs), this.parseOtherImage(imgs)]).then(
  9. ([svgXmls, imgUrls]) => {
  10. // svg xml
  11. svgs.forEach((svg, idx) => {
  12. // 替换
  13. xml = xml.replace(
  14. new RegExp(`<image[^><]* xlink:href="${svg}"[^><]*/>`),
  15. svgXmls[idx].match(/<svg[^><]*>.*<\/svg>/)?.[0] ?? '' // 仅保留 svg 结构
  16. )
  17. })
  18. // base64
  19. imgs.forEach((img, idx) => {
  20. // 替换
  21. xml = xml.replace(`"${img}"`, `"${imgUrls[idx]}"`)
  22. })
  23. // 替换完成
  24. resolve(xml)
  25. }
  26. )
  27. })
  28. }

替换 svg blob: 链接

批量 fetch svg blob: 链接,获得 xml 内容:

  1. // 替换 svg blob: 链接
  2. parseSvgImage(urls: string[]): Promise<string[]> {
  3. return new Promise((resolve) => {
  4. if (urls.length > 0) {
  5. Promise.all(urls.map((o) => fetch(o))).then((rs: Response[]) => {
  6. // fetch
  7. // 替换为 svg 嵌套
  8. Promise.all(rs.map((o) => o.text())).then((xmls: string[]) => {
  9. // svg xml
  10. resolve(xmls)
  11. })
  12. })
  13. } else {
  14. resolve([])
  15. }
  16. })
  17. }

替换其他 image 链接

批量 fetch 图片链接,获得 base64 链接:

  1. // blob to base64 url
  2. blobToBase64(blob: Blob, type: string): Promise<string> {
  3. return new Promise((resolve) => {
  4. const file = new File([blob], 'image', { type })
  5. const fileReader = new FileReader()
  6. fileReader.readAsDataURL(file)
  7. fileReader.onload = function () {
  8. resolve((this.result as string) ?? '')
  9. }
  10. })
  11. }
  12. // 替换其他 image 链接
  13. parseOtherImage(urls: string[]): Promise<string[]> {
  14. return new Promise((resolve) => {
  15. if (urls.length > 0) {
  16. Promise.all(urls.map((o) => fetch(o))).then((rs: Response[]) => {
  17. // fetch
  18. // 替换为 base64 url image
  19. Promise.all(rs.map((o) => o.blob())).then((bs: Blob[]) => {
  20. // blob
  21. Promise.all(bs.map((o) => this.blobToBase64(o, 'image/*'))).then((urls: string[]) => {
  22. // base64
  23. resolve(urls)
  24. })
  25. })
  26. })
  27. } else {
  28. resolve([])
  29. }
  30. })
  31. }

过程示例

通过 canvas2svg 获得原始的 rawSvg xml 内容:

image

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="428" height="448">
  3. <defs/>
  4. <g>
  5. <rect fill="#FFFFFF" stroke="none" x="0" y="0" width="428" height="448"/>
  6. <g transform="matrix(1,0,0,1,69,80)">
  7. <!-- gif 图片 -->
  8. <image width="200" height="200" preserveAspectRatio="none" xlink:href="data:image/png;base64,略..."/>
  9. <g transform="translate(0,0)"/>
  10. </g>
  11. <g transform="matrix(1,0,0,1,17,22)">
  12. <!-- png 图片 -->
  13. <image width="64" height="64" preserveAspectRatio="none" xlink:href="/src/assets/img/png/2.png"/>
  14. <g transform="translate(0,0)"/>
  15. </g>
  16. <g transform="matrix(1,0,0,1,228,232)">
  17. <!-- svg 图片 -->
  18. <image width="200" height="200" preserveAspectRatio="none" xlink:href="blob:http://localhost:5173/da9ddae7-2ac7-47fb-99c0-e7171aa41655"/>
  19. <g transform="translate(0,0)"/>
  20. </g>
  21. </g>
  22. </svg>

替换之后:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="428" height="448">
  3. <defs/>
  4. <g>
  5. <rect fill="#FFFFFF" stroke="none" x="0" y="0" width="428" height="448"/>
  6. <g transform="matrix(1,0,0,1,69,80)">
  7. <!-- gif 图片 base64 -->
  8. <image width="200" height="200" preserveAspectRatio="none" xlink:href="data:image/*;base64,略..."/>
  9. <g transform="translate(0,0)"/>
  10. </g>
  11. <g transform="matrix(1,0,0,1,17,22)">
  12. <!-- png 图片 base64 -->
  13. <image width="64" height="64" preserveAspectRatio="none" xlink:href="data:image/*;base64,略..."/>
  14. <g transform="translate(0,0)"/>
  15. </g>
  16. <g transform="matrix(1,0,0,1,228,232)">
  17. <!-- svg 内嵌 -->
  18. <svg class="icon" width="200px" height="200.00px" viewBox="0 0 1024 1024" version="1.1">
  19. <path d="M512 0c282.763636 0 512 229.236364 512 512S794.763636 1024 512 1024 0 794.763636 0 512 229.236364 0 512 0z m0 11.636364C235.659636 11.636364 11.636364 235.659636 11.636364 512s224.023273 500.363636 500.363636 500.363636 500.363636-224.023273 500.363636-500.363636S788.340364 11.636364 512 11.636364z m-114.781091 683.927272c38.388364 6.632727 63.767273 22.853818 103.133091 61.556364l7.563636 7.528727 19.502546 19.921455c4.736 4.770909 9.262545 9.216 13.637818 13.370182l6.434909 6.004363c1.047273 0.965818 2.094545 1.908364 3.141818 2.839273l6.132364 5.352727c30.196364 25.728 53.946182 35.735273 87.226182 36.398546 69.992727 1.361455 119.936-22.027636 150.621091-70.272l2.094545-3.397818 9.972364 6.004363c-32.756364 54.318545-87.354182 80.779636-162.909091 79.290182-41.262545-0.814545-68.817455-14.650182-107.333818-50.583273l-6.714182-6.376727-6.946909-6.818909-7.226182-7.272727-15.709091-16.069819-7.284364-7.26109c-37.922909-37.329455-61.777455-52.596364-97.314909-58.740364-67.397818-11.659636-122.705455 10.24-166.725818 66.106182l-2.792727 3.607272-9.262546-7.028363c47.045818-61.940364 107.578182-86.807273 180.759273-74.158546z"/>
  20. </svg>
  21. <g transform="translate(0,0)"/>
  22. </g>
  23. </g>
  24. </svg>

关于 gif,实测内嵌于 svg 中是无法显示的,现在除了 svg 图片素材节点,其它图片素材统一按静态图片处理。

image

磁贴

增加了对 stage 逻辑边界的磁贴:
image

其它调整

staget 逻辑区域

原来 stage 的逻辑区域和比例尺的区域是重叠一致的(大小一致,默认根据比例尺大小对齐 0 点而已),实在有点变扭,可能会让人产生疑惑。
现已经调整 stage 的逻辑区域即为默认可视区域(区别可以观察红色虚线框的改变)。
顺便使得预览框的交互优化的更符合直觉。

官方的 API 的 Bug

Bug: 恢复 JSON 时候,如果存在已经被放大缩小点元素,点击选择无效
原因不详,Hack 了一下,暂时可以消除影响。

接下来,计划实现下面这些功能:

  • 对齐效果
  • 连接线
  • 等等。。。

是不是值得更多的 Star 呢?勾勾手指~

源码

gitee源码

示例地址

原文链接:https://www.cnblogs.com/xachary/p/18178115

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号