java+合并svg图片,将SVG和.JPG合并为一个图像?

I have an website using SVG/VML (via Raphael JS) setup in a mapping application where the SVG is used to display graphics atop a backdrop map image. This works very well onscreen, and for printing hardcopy maps with overlays. Where this setup falls apart however is when the user wants to save the map image with the SVG overlay to a local .JPG file.

More specifically, using the standard right-click functionality of most browsers to "Save image as..." does not work when there is an SVG/VML element sitting atop the image. Right-click on the map, and the user can save the map image, but without the overlay. Right-click on the overlaid SVG element, and the best the user gets is the ability to inspect the element or save out some HTML (it varies by browser).

So my main question here is; Is it possible to take an image and an SVG element and combine them (preferably client-side, though I'm open to options) into one "flattened" image, .JPG, .PNG or otherwise, that can then be right-clicked and saved, or downloaded to a user's PC upon request?

解决方案

I'm afraid you're gonna have a tough time attempting to render SVG on a Canvas element just like that due to security constraints (I could not get this working in Firefox at all for instance).

Here's an idea though:

Place your image inside the SVG DOM using the svg tag

Pass your SVG code through the canvg library

Use the toDataURL method of canvg to generate the image

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
合并两个SVG文件为一个SVG文件,您可以使用Fabric.js库进行操作。下面是一个示例代码,演示了如何使用Fabric.js将两个SVG文件合并一个SVG文件: ```javascript // 引入Fabric.js库 import { fabric } from 'fabric'; // 创建canvas const canvas = new fabric.Canvas('canvas'); // 加载第一个SVG文件 fabric.loadSVGFromURL('path/to/first.svg', (objects, options) => { const firstSvg = fabric.util.groupSVGElements(objects, options); // 加载第二个SVG文件 fabric.loadSVGFromURL('path/to/second.svg', (objects, options) => { const secondSvg = fabric.util.groupSVGElements(objects, options); // 将第二个SVG对象添加到第一个SVG对象中 firstSvg.addWithUpdate(secondSvg); // 将合并后的SVG对象添加到canvas中 canvas.add(firstSvg); // 将canvas导出为合并后的SVG文件 const mergedSvg = canvas.toSVG(); // 打印合并后的SVG代码 console.log(mergedSvg); }); }); ``` 这段代码首先创建一个canvas对象,然后使用`fabric.loadSVGFromURL`加载第一个SVG文件,并将其转换为Fabric.js的对象。接着,再加载第二个SVG文件,并将其转换为Fabric.js的对象。然后,使用`addWithUpdate`方法将第二个SVG对象添加到第一个SVG对象中。最后,使用`toSVG`方法将canvas导出为合并后的SVG文件,并将其打印在控制台上。 请确保替换代码中的`'path/to/first.svg'`和`'path/to/second.svg'`为实际的SVG文件路径。还需要在HTML中创建一个id为`canvas`的canvas元素,以便Fabric.js可以将合并后的SVG渲染到其中。 希望这个示例能帮助到您!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值