首页 > 解决方案 > How can I fill multiple similar paths in two separate SVG images?

问题描述

I am making website where user interacts with svg and fills it with color on click, i managed to make path fill on click, but the issue i have currently is because there is 2 svg and when u click to fill some path on svg1 sometimes svg2 path needs to be filled aswell. I was thinking to add some classes to svg and then check if svg1 path has same class as svg2 path and then fill both paths based on that condition. I was wondering if there is some easier way.Also not all paths should be filled with same color only some, and i dont see any pattern in it. I also thought of adding some metadata but that might complicate things even further. here is what i have currently how i want it to work

  mounted() {
    let self = this;
    this.$nextTick(() => {
      Array(...document.getElementsByTagName('svg')).forEach((obj) => {
        console.log(obj)
        let children = obj.getElementsByTagName('*')
        console.dir(children)
        let arr = Array(...children);
        arr.forEach(function(item) {
          if (item.classList.contains("frontstich")) {
            item.style.fill = 'black'
          }

          //I WAS THINKING OF ADDING CONDITION MENTIONED ABOVE HERE

          else {
            item.addEventListener('click', function() {
              item.style.fill = self.color;
            })
          }
        });

      })
    })
  }

this is my mounted section in vue component

标签: javascriptanimationsvgvue.js

解决方案


如果如您所说,没有其他模式可以告诉您应该绘制什么,那么您需要自己指定它。

您可以使用类或 id 来做到这一点,这真的不是很容易做到,特别是如果您有一个大的 SVG 文件。

很久以前我在这里做过类似的事情https://codepen.io/rafaelcastrocouto/pen/xnclb

请注意,对于某些元素,我正在更改渐变停止颜色而不是填充属性,但这基本上是相同的想法。我制作了一个对象来映射所有颜色,这使我可以删除 if 语句。

 ch[i].attributes['stop-color'].value="#"+colors[names[ncolor]][j];

您还可以在外部 CSS 中列出所有颜色,只需更改 SVG 根元素的类名,但您仍然需要指定要绘制的内容。


推荐阅读