【问题标题】:Background image to SVG choropleth map using D3使用 D3 将背景图像转换为 SVG 等值线图
【发布时间】:2013-12-30 22:52:22
【问题描述】:

我正在美国各州的 D3 中制作一个等值线地图,并且已经有了使用填充以纯色背景渲染地图的代码。

但是,我希望状态路径的填充是图像。我尝试将路径 background-image 设置为 img 的 URL,但这不起作用。

我该怎么做?我还想为每个州填充不同的图像。

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);
    });
});

【问题讨论】:

标签: javascript css svg d3.js


【解决方案1】:

正如 Superboggly 指出的,首先定义一个pattern,然后使用它。

定义示例:

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

然后将您的fill 设置为url(#chloroplethbackground)

原来是这样:

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);
    });
});

【讨论】:

    猜你喜欢
    • 2015-04-11
    • 1970-01-01
    • 2016-07-30
    • 1970-01-01
    • 2019-10-02
    • 2021-08-04
    • 2014-03-24
    相关资源
    最近更新 更多