簡體   English   中英

在 chrome 中使用 javascript 設置 SVG 屬性

[英]Setting SVG Attributes with javascript in chrome

也許這是 Chrome (88.0.4324.150) svg 渲染的錯誤,它似乎只能在此瀏覽器中重現。 但也許我做錯了什么?

當我使用 setAttribute 使用 javascript 動態且重復地設置填充模式屬性時,盡管在檢查器中正確顯示,但它並不總是可見應用。 如果 window 得到重繪,例如。 通過調整大小,它突然被應用。

為什么屬性變化不顯示? 我是否錯過了一些(未記錄的)更新調用,或者這只是一個瀏覽器錯誤?

您可以在代碼段中看到問題,反復單擊填充模式鏈接。

 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>

絕對是一個錯誤。
getComputedstyle(polygon).fill-rule顯示正確的fill-rule state,但未應用。

有趣.. 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 state重繪多邊形
(但您可能會通過動畫獲得不需要的副作用)

  • 下面的 SO 代碼段在點擊時有不正確的行為(在 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM