Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing SVG image color with javascript

Tags:

javascript

svg

I am trying to alter svg image colors with javascript. Is this possible? Can I load it as an object and then somehow have access to the color/image-data.

Every respone or tip is highly appreciated!

like image 918
Potney Switters Avatar asked Mar 26 '12 13:03

Potney Switters


People also ask

How do you change SVG fill color in JS?

To change SVG image color with JavaScript, we can set the fill attribute value. const svgElement = document. getElementById("svg"); svgElement. style.

How do I change the color of an SVG image?

To simply change the color of the svg : Go to the svg file and under styles, mention the color in fill.

How do I change dynamic color in SVG?

It's an SVG element with an image behind it, and a vector shape (path element) drawn over the part(s) you want the color to change. You simply change the fill color of your path element, and use the CSS property mix-blend-mode: multiply to stain that color onto the image.

Can JavaScript be applied to SVG?

Like HTML, SVGs are represented using the Document Object Model (DOM) and so can be manipulated with Javascript relatively easily, especially if you are familiar with using JS with HTML.


1 Answers

Sure, here is an example (standard HTML boilerplate omitted):

<svg id="svg1" xmlns="http://www.w3.org/2000/svg" style="width: 3.5in; height: 1in">    <circle id="circle1" r="30" cx="34" cy="34"               style="fill: red; stroke: blue; stroke-width: 2"/>    </svg>  <button onclick="circle1.style.fill='yellow';">Click to change to yellow</button>
like image 105
peter Avatar answered Oct 09 '22 11:10

peter