更改SVG填充循环

时间:2019-01-31 18:04:15

标签: javascript svg

我有一个简单的SVG插图,有什么办法可以不断改变它的颜色吗?就像循环不停地随机改变颜色。

这是我的svg

<svg width="533" height="499" viewBox="0 0 533 499" fill="none" xmlns="http://www.w3.org/2000/svg">

3 个答案:

答案 0 :(得分:3)

这就是我要这样做的方式:我使用颜色hsl进行填充,并使用requestAnimationFrame对颜色的色调进行动画处理。希望对您有所帮助。

let p1 = document.querySelectorAll("path")[0];
let p2 = document.querySelectorAll("path")[1]
let h = 0;

function changeColor(){
  
  window.requestAnimationFrame(changeColor);
  h+=.5;
  h2=210+h;
  p1.setAttributeNS(null,"fill", `hsl(${~~h},100%,50%)`);
  p2.setAttributeNS(null,"fill", `hsl(${~~h2},100%,50%)`);
}

changeColor()
<svg width="533" height="499" viewBox="0 0 533 499" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M258.089 59.6035C309.803 -3.94652 379.363 78.1818 407.679 127.19C352.338 67.4782 301.718 129.7 287.076 167.787C272.435 205.874 233.694 210.043 205.199 217.679C187.359 222.459 146.446 248.26 128.6 264.085C109.864 289.466 48.3081 292.846 41.8378 268.698C27.0852 213.64 95.5238 148.37 137.644 123.97C163.705 101.458 206.375 123.154 258.089 59.6035Z" fill="blue"/>
<path d="M448.323 394.788C427.389 384.661 420.75 356.279 420.047 343.354C441.009 284.421 527.63 350.762 528.167 368.218C528.703 385.674 474.491 407.447 448.323 394.788Z" fill="red"/>
</svg>

答案 1 :(得分:1)

选择该元素并递归调用一个函数,该函数设置要使用随机十六进制重新着色的SVG元素的BigInt属性。

import android.content.Context
import android.support.v7.widget.AppCompatButton
import android.util.AttributeSet

class FadedDisableButton : AppCompatButton {
    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr)

    override fun setEnabled(enabled: Boolean) {
        alpha = when {
            enabled -> 1.0f
            else -> 0.5f
        }
        super.setEnabled(enabled)
    }
}
fill
const recolor = element => {
  const randomColor = '#'+Math.floor(Math.random()*16777215).toString(16)
  
  circle.setAttribute('fill', randomColor)
  
  setTimeout(() => recolor(element), 600)
}

recolor(document.querySelector('#circle'))

答案 2 :(得分:-1)

fill<svg>多年平均值的工作。其元素。您可以更改其background

    function random_rgba() {
        var o = Math.round, r = Math.random, s = 255;
        return 'rgba(' + o(r()*s) + ',' + o(r()*s) + ',' + o(r()*s) + ',' + r().toFixed(1) + ')';
    }
    function changeColor(){
    	document.querySelector('svg').style.background = random_rgba();
    }
    setInterval(changeColor,200);
<svg width="533" height="499" viewBox="0 0 533 499" fill="none" xmlns="http://www.w3.org/2000/svg">