这里是 SVG 新手。我正在尝试进行一项改进,其中在将 SVG map 转换为 PNG 期间包含国家/地区标签(如 <div>
)。
要转换的 map 如下所示:
这就是它在 DOM 中的样子。 div
要包含的标签已突出显示。
这是我到目前为止尝试过的:
var svg = $('svg', $(svgParentId));
// append map labels // From this line...
var outerHtmlColl = $(svgParentId).find('.marker-label'); //
//
_.forEach(outerHtmlColl, function(item){ //
svg = svg.append(item.outerHTML); //
}); // ...to this line
// check whether style should be applied
if (styleSheet) {
var styles = loadStyles([styleSheet]);
var defs = $('defs', svg);
if (!defs.length) {
svg.prepend('<defs></defs>');
defs = $('defs', svg).first();
}
var style = $('style', defs);
if (!style.length) {
defs.prepend('<style type="text/css"></style>');
style = $('style', defs).first();
style.html(styles);
}
}
var serializer = new XMLSerializer();
var svgStr = serializer.serializeToString(svg[0]);
var canvas = $('#hiddenCanvas')[0];
canvas.width = width;
canvas.height = height;
canvg(canvas, svgStr,
{
ignoreDimensions: true, //does not try to resize canvas
scaleWidth: width,
scaleHeight: height,
renderCallback: function () {
var pngImg = canvas.toDataURL("image/png");
func(pngImg.substring(22));
}
}
);
不幸的是,这不起作用,如下所示:
我不确定我到底错过了什么(或者这是否可能...)。任何意见将不胜感激。
谢谢。
最佳答案
Div 不是有效的 SVG 子元素,因此将它们移动到 SVG 中是行不通的。
您应该通过将 div 元素转换为 <text>
将 div 中的文本移动到 SVG 中元素。使用文本元素的 x 和 y 属性在 SVG 中定位标签。
关于javascript - 将 SVG 转换为 PNG 时如何包含 <div> 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47509968/