代码之家  ›  专栏  ›  技术社区  ›  Joschi

在chrome中使用javascript设置SVG属性

  •  0
  • Joschi  · 技术社区  · 5 年前

    可能这是Chrome(88.0.4324.150)svg呈现的一个bug,它似乎只能在这个浏览器中复制。但也许我做错了什么?

    当我使用setAttribute用javascript动态地重复设置fill mode属性时,它并不总是可见的,尽管在检查器中正确地显示了它。如果窗口重新绘制(例如通过调整大小),它会突然应用。

    为什么属性更改没有出现?我是错过了一些(未记录的)更新电话,还是这只是一个浏览器错误?

    您可以在代码段中看到问题,反复单击填充模式链接。

    const doc = document.createElementNS("http://www.w3.org/2000/svg", 'svg');
    doc.setAttribute("xmlns", "http://www.w3.org/2000/svg");
    doc.setAttribute("viewBox", "0 0 200 200");
    doc.setAttribute("width", 200);
    doc.setAttribute("height", 200);
    const polygon = document.createElementNS("http://www.w3.org/2000/svg", 'polygon');
    polygon.setAttribute('stroke', 'black');
    polygon.setAttribute('stroke-width', 3);
    polygon.setAttribute('fill', 'blue');
    polygon.setAttribute('fill-rule', 'evenodd');
    polygon.setAttribute('points', '150,100,59,129,115,52,115,147,59,70');
    
    doc.appendChild(polygon);
    document.getElementById('dest').appendChild(doc);
    
    // setting up event handlers
    [...document.querySelectorAll('[data-color]')].forEach((el) =>
      el.addEventListener(
        "click",
        (e) =>
        polygon.setAttribute('fill', e.target.getAttribute('data-color'))
      )
    );
    [...document.querySelectorAll('[data-fill-rule]')].forEach((el) =>
      el.addEventListener(
        "click",
        (e) =>
        polygon.setAttribute('fill-rule', e.target.getAttribute('data-fill-rule'))
      )
    );
    <a href="#" data-color="red">set red</a> - 
    <a href="#" data-color="green">set green</a> - 
    <a href="#" data-color="blue">set blue</a><br> Problematic, swap multiple: <a href="#" data-fill-rule="evenodd">set evenodd</a>
    <a href="#" data-fill-rule="nonzero">set nonzero</a>
    <div id="dest"></div>
    0 回复  |  直到 5 年前
        1
  •  0
  •   Danny '365CSI' Engelman    5 年前

    绝对是个虫子。
    getComputedstyle(polygon).fill-rule 显示正确的 fill-rule

    有趣。。 浏览器兼容性信息:
    https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/fill-rule

    移动 多边形 里面 SVG具有: this.closest('svg').append(this);

    如果您有更复杂的SVG,您可以使用 在前面插入 :
    https://developer.mozilla.org/en-US/docs/Web/API/Node/insertBefore
    移动元素“就位” 它本身

    重画 具有正确形状的多边形 填充规则
    (但动画可能会产生不必要的副作用)

    • 按住Ctrl键单击以使用变通方法
      (当然,当上一次单击未应用状态时,会单击2次)

    <b>Click Red color to toggle fill-rule: evenodd/nonzero</b><br>
    
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="50 50 100 100" width="200">
    <polygon fill-rule="evenodd" fill="red" points="150,100,59,129,115,52,115,147,59,70" 
     onclick="let fr = this.getAttribute('fill-rule')=='evenodd' ? 'nonzero' : 'evenodd';
              this.setAttribute('fill-rule', fr );
              if (event.ctrlKey) this.closest('svg').append(this)"></polygon>
    </svg>
    推荐文章