使用 React-Leaflet,我尝试为使用 URI 编码的 SVG 制作的标记提供自定义图标。 当提供一次十六进制颜色时,一切正常。
var stopCircleSvg =
'<svg xmlns="http://www.w3.org/2000/svg" width="67" height="67">'+
'<g>' +
'<circle id="1" cx="34" cy="34" r="3" stroke="#D7629B" stroke-width="1.5" fill="none"/>' +
'<circle id="2" cx="34" cy="34" r="1" fill="red" />' +
'</g>' +
'</svg>';
var url = encodeURI("data:image/svg+xml," + stopCircleSvg).replace("#", "%23");
var CustomIcon = Icon.extend({
options: {
iconSize: [stopCircleSize, stopCircleSize],
iconAnchor: [stopCircleSize / 2, stopCircleSize / 2],
},
});
....
icon={
new CustomIcon({ iconUrl: url })
}
当为更多元素提供十六进制颜色时,SVG 会损坏。
var stopCircleSvg =
'<svg xmlns="http://www.w3.org/2000/svg" width="67" height="67">'+
'<g>' +
'<circle id="1" cx="34" cy="34" r="3" stroke="#D7629B" stroke-width="1.5" fill="none"/>' +
'<circle id="2" cx="34" cy="34" r="1" fill="#D7629B" />' +
'</g>' +
'</svg>';
var url = encodeURI("data:image/svg+xml," + stopCircleSvg).replace("#", "%23");
最佳答案
你应该打电话encodeURIComponent而不是encodeURI,那么您根本不需要替换调用。
var stopCircleSvg =
'<svg xmlns="http://www.w3.org/2000/svg" width="67" height="67">'+
'<g>' +
'<circle id="1" cx="34" cy="34" r="3" stroke="#D7629B" stroke-width="1.5" fill="none"/>' +
'<circle id="2" cx="34" cy="34" r="1" fill="#D7629B" />' +
'</g>' +
'</svg>';
var url = "data:image/svg+xml," + encodeURIComponent(stopCircleSvg);
document.getElementById("i").setAttribute("src", url);
img {
transform: scale(4);
}
<img id="i">
关于使用 EncodeURI 创建的 SVG 不适用于 React-leaflet 上的 2 个十六进制颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73798194/