我想将 svg 圆圈的填充颜色从一种颜色淡化为另一种颜色,比如从红色淡化为黑色。
<svg height="100" width="100">
<circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" fade-to="black"/>
</svg>
我会用什么来代替 fade-to="black"
?
最佳答案
基本上你只需要改变圆的 fill
属性:
- CSS(例如:悬停)
- svg SMIL 动画(使用
begin="click"
) - JavaScript(例如点击 eventListner)
let dotJs = document.querySelector('#dotJs');
dotJs.addEventListener('click', function(e) {
e.currentTarget.classList.toggle('active')
})
circle {
transition: 0.5s fill;
}
.active {
fill: #000
}
#dotCSS:hover {
fill: #000
}
<p>Css hover</p>
<svg height="100" width="100">
<circle id="dotCSS" cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
</svg>
<p>JS click</p>
<svg height="100" width="100">
<circle id="dotJs" cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
</svg>
<p>SMIL click</p>
<svg height="100" width="100">
<circle id="dot" cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
<animate id="startAnimation"
href="#dot"
attributeName="fill"
from="red"
to="black"
begin="click"
dur="0.5s"
repeatCount="0"
fill="freeze"
/>
</svg>
检查 Mike Harris' post: Toggling SVG without any scripting一个更高级的 svg 示例。
关于对象的 SVG 淡化颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72807028/