damianstasik / vue-svg-loader

🔨 webpack loader that lets you use SVG files as Vue components
https://vue-svg-loader.js.org
MIT License
645 stars 86 forks source link

Change style attribute value from svg #146

Closed robertaecosta closed 3 years ago

robertaecosta commented 3 years ago

Hello everyone,

I need to change fill color from some path elements inside my .svg. How should I approach this?

We can pretend this is my .svg file:

<svg [...]>
  <defs>
    [...]
  </defs>
  <path
           style="clip-rule:evenodd;display:inline;fill:#00ff00;fill-rule:evenodd;stroke:#000000;stroke-width:0.03818662;stroke-linejoin:bevel;image-rendering:optimizeQuality;shape-rendering:geometricPrecision;text-rendering:geometricPrecision"
           id="tx-port-1"
           d="m 55.931318,146.94475 c 0,-0.40091 -0.325738,-0.72665 -0.726648,-0.72665 -0.400909,0 -0.726648,0.32574 -0.726648,0.72665 0,0.40091 0.325739,0.72665 0.726648,0.72665 0.40091,0 0.726648,-0.32574 0.726648,-0.72665 z"
           class="fil15 str0" />
  <path
           style="clip-rule:evenodd;display:inline;fill:#00ff00;fill-rule:evenodd;stroke:#000000;stroke-width:0.03818662;stroke-linejoin:bevel;image-rendering:optimizeQuality;shape-rendering:geometricPrecision;text-rendering:geometricPrecision"
           id="tx-port-2"
           d="m 55.931318,146.94475 c 0,-0.40091 -0.325738,-0.72665 -0.726648,-0.72665 -0.400909,0 -0.726648,0.32574 -0.726648,0.72665 0,0.40091 0.325739,0.72665 0.726648,0.72665 0.40091,0 0.726648,-0.32574 0.726648,-0.72665 z"
           class="fil15 str0" />
</svg>

And this is my template, if it matters

<template>
    <MySVG ref="mysvg"/>
</template>

It would be ideal for me if we could reference the elements by its id's ('tx-port-1' and 'tx-port-2'). I can edit the .svg file in any way if necessary.

I believe this should be very simple, so I'm sorry if this is a dumb question, but after a whole day searching I still can't find any useful resource to help me with this. Can anyone help here?

Edit: fixing code formatting

robertaecosta commented 3 years ago

Well, I figured out a solution. It was to use d3, of course! I thought I could solve my life without adding another dependency to the project, but I think it wasn't possible.

If anyone's interested, here is my working JS code:

import * as d3 from 'd3';
let ledElement = d3.select('.tx-port-1');
ledElement.style("fill", green)

(I had to add a class to the elements on the .svg so I could select them from the JS, because I couldn't select them via id for some reason and don't have a lot of time to spend on this right now.) bonus, adding a blinking animation to the element:

ledElement.append("animate")
                    .attr("attributeType", "XML")
                    .attr("attributeName", "fill")
                    .attr("values", "#ff0000;#ff0000;#999999")
                    .attr("dur", "1s")
                    .attr("repeatCount", "indefinite");