简体   繁体   English

使用D3的背景图像到SVG等值线图

[英]Background image to SVG choropleth map using D3

I'm putting together a choropleth map in D3 of US States and already have the code to render the map with solid colored backgrounds using fill. 我在美国各州的D3中整理了一个等值区域地图,并且已经有了使用填充渲染带有纯色背景的地图的代码。

However, I want the fill of the state paths to be an image. 但是,我希望状态路径的填充是一个图像。 I tried setting the path background-image to the img's URL, but that didn't work. 我尝试将路径背景图像设置为img的URL,但这不起作用。

How can I do this? 我怎样才能做到这一点? I'd also like to fill each state a different image. 我还想给每个州填写一个不同的图像。

var svg = d3.select("#map").append("svg")
    .attr("width", width)
    .attr("height", height);

svg.append("rect")
    .attr("class", "background")
    .attr("fill","none")
    .attr("width", width)
    .attr("height", height);

var g = svg.append("g")
    .attr("class", "states");

$(document).ready(function() {
    d3.json("us-states.json", function(json) {
        var features = json.features;
        g.selectAll("path")
            .data(json.features)
            .enter()
            .append("path")
            .attr("d", path)
            .attr("fill", "purple")
            .attr("stroke","white")
            .attr("stroke-width", 1);
    });
});

As Superboggly points out, first define a pattern , then use it. 正如Superboggly指出的那样,首先定义一个pattern ,然后使用它。

Definition example: 定义示例:

<defs>
    <pattern id="chloroplethbackground" patternUnits="userSpaceOnUse" width="??" height="??">
        <image xlink:href="bg.jpg" x="0" y="0" width="??" height="??" />
    </pattern>
</defs>

Then set your fill to url(#chloroplethbackground) 然后将fill设置为url(#chloroplethbackground)

So it will be: 所以它将是:

var svg = d3.select("#map").append("svg")
    .attr("width", width)
    .attr("height", height);

svg.append("rect")
    .attr("class", "background")
    .attr("fill","none")
    .attr("width", width)
    .attr("height", height);

var g = svg.append("g")
    .attr("class", "states");

$(document).ready(function() {
    d3.json("us-states.json", function(json) {
        var features = json.features;
        g.selectAll("path")
            .data(json.features)
            .enter()
            .append("path")
            .attr("d", path)
            .attr("fill", "url(#chloroplethbackground)")
            .attr("stroke","white")
            .attr("stroke-width", 1);
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM