使用 EncodeURI 创建的 SVG 不适用于 React-leaflet 上的 2 个十六进制颜色

标签 svg react-leaflet

使用 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 })
  }

Work well with regular color and hex color

当为更多元素提供十六进制颜色时,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");

SVG breaks

最佳答案

你应该打电话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/

相关文章:

react-leaflet - 我如何为玩笑测试模拟传单?

reactjs - 如何修复从 firestore 数据库获取数据时 react 中的状态更新

javascript - React Leaflet : Dynamic Markers, 无法读取属性 'addLayer'

javascript - 使用 D3 向静态 SVG 动态添加工具提示

javascript - 如何将 javascript 与 svg 结合使用?

javascript - Highcharts 气泡图,自定义标记

javascript - 如何在 react 传单中制作椭圆形?

javascript - 如何循环遍历 SVG 中的路径元素?

html - 相当于SVG中的背景位置百分比(%)

javascript - 将传单插件添加到 React-Leaflet