Dynamically Color SVG Polygons with JavaScript

  Kiến thức lập trình

I’m parsing some data that contains a list of points that define a polygon and an integer indicating what class the polygon belongs to. I would like to make each class a different color but I don’t know how many there will be ahead of time so I’d like to do this dynamically in JavaScript.

Here is some code that creates some of these polygons. In the JavaScript I apply a second class to the anchors and get the result that I want. However, since I want to do this dynamically, I would like to do this without having a predefined style in the CSS other than the base style. There is also a line that’s commented out that I thought would achieve this but the behavior is incorrect. I’ve tried many other things getting more and more complex but it seems like this should be straight forward to do. I basically want to inherit the base class behaviors and modify a single property (fill in my case). What’s a clean way to do this in JavaScript?

CSS

svg {
    display:block;
    width:100%; height:auto;
    margin:0 auto;
}

a { 
    stroke:#070000; 
    stroke-width:1.0;
    fill:#77777777;
    transition: fill .15s;
}

/* Clear mask on mouseover to make the segment more visible */
.segment:hover { fill:#00000000; stroke-width:0.0; }

/* Use bright color to show focus */
.segment:focus { fill:orange; }

/* New color for testing */
.test {fill:#00007777; }

HTML

<!DOCTYPE html>

<html>

<head>
    <title>TBD</title>
    <link rel="stylesheet" href="/static/css/styles.css">
</head>

<body>
    <div class="img-overlay-wrap" width="200" height="200">
        <img id="background_img" src="https://placehold.it/200x200">
        <svg id="mySvg" viewbox="0 0 200 200">
            <a class=segment href="#"> <polygon points="0 0 100 0 100 100 0 100"         /> </a>
            <a class=segment href="#"> <polygon points="100 0 200 0 200 100 100 100"     /> </a>
            <a class=segment href="#"> <polygon points="0 100 100 100 100 200 0 200"     /> </a>
            <a class=segment href="#"> <polygon points="100 100 200 100 200 200 100 200" /> </a>
        </svg>
    </div>

    <script src="/static/temp.js"></script>
</body>

</html>

JavaScript

function init(){
    var anchors = document.getElementById("mySvg").querySelectorAll("a");

    for (var i = 0; i < anchors.length; i++) {
        anchors[i].classList.add('test')            // This works
        //anchors[i].style.fill = "#00ff0077"         // This does not
    }
}

init()

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT