【问题标题】:Setting SVG Attributes with javascript in chrome在 chrome 中使用 javascript 设置 SVG 属性
【发布时间】:2021-05-16 23:29:10
【问题描述】:

也许这是 Chrome (88.0.4324.150) svg 渲染的错误,它似乎只能在此浏览器中重现。但也许我做错了什么?

当我使用 setAttribute 使用 javascript 动态且重复地设置填充模式属性时,尽管在检查器中正确显示,但它并不总是可见应用。如果窗口得到重绘,例如。通过调整大小,它突然被应用。

为什么属性变化不显示?我是否错过了一些(未记录的)更新调用,或者这只是一个浏览器错误?

你可以在sn-p中看到问题,反复点击填充模式链接。

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>

【问题讨论】:

  • 如果您发现 Chrome 错误,请报告给Chrome's bugtracker
  • 好的,如果没有人发现我做错了什么,我会做的

标签: javascript google-chrome svg attributes


【解决方案1】:

绝对是一个错误。
getComputedstyle(polygon).fill-rule 显示正确的fill-rule 状态,但未应用。

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

解决方法是将多边形移动内部 SVG:this.closest('svg').append(this);

如果您有更复杂的 SVG,您可以使用 insertBefore
https://developer.mozilla.org/en-US/docs/Web/API/Node/insertBefore
将元素“就地”移动 自身之前

移动重绘具有正确fill-rule状态的多边形
(但你可能会得到不想要的副作用)

  • SO sn-p 下面的点击行为不正确(在 Chromium 浏览器中)

  • 按住 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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-06
    • 1970-01-01
    • 1970-01-01
    • 2012-01-17
    • 1970-01-01
    • 2011-07-08
    • 2013-08-04
    • 1970-01-01
    相关资源
    最近更新 更多