svg中的patternTransform不适用于整个模式

时间:2017-01-17 20:47:23

标签: javascript d3.js svg

我使用D3中的模式将图像放在节点内,我可以成功渲染图像。我正在使用标志精灵,只想为每个标志剪一小部分。我能够为2/3的图像执行此操作,但出于某种原因,它不会在110px以下显示图像的任何部分。图像是256乘176。

javascript
        //canvas
    var svg = d3.select("#chartContainer")
        .append('svg')
        .attr("width", 400)
        .attr("height", 400)
        .append('g');

        svg.append("pattern")
            .attr("id", "us")
            ///should be transformed to the US coordinates but the Algerian Flag appears
            .attr("patternTransform", "translate(-128, -154)")
            //this correctly shows the Canadian Flag
            //.attr("patternTransform", "translate(-16, -22)")
            .attr("width", 16)
            .attr("height", 11)
            .append("image")
            .attr("xlink:href", "https://dl.dropboxusercontent.com/u/5258675/flags.png")
            .attr("width", 256)
            .attr("height", 176);

    svg.append("rect")
        .attr("width", 16)
        .attr("height", 11)
        .attr("x", 50)
        .attr("y", 50)
        .attr("fill", "url(#us)");

这也是一个codepen:https://codepen.io/andrewgi/pen/oBYMdp?editors=1010

此处可以看到图像精灵的坐标:https://dl.dropboxusercontent.com/u/5258675/flags.png

1 个答案:

答案 0 :(得分:0)

最简单的方法可能是完全删除patternTransform并改为transform上的<image>

svg.append("pattern")
    .attr("id", "us")
    .attr("width", 16)
    .attr("height", 11)
  .append("image")
    .attr("xlink:href", "https://dl.dropboxusercontent.com/u/5258675/flags.png")
    .attr("transform", "translate(-128, -154)")
    .attr("width", 256)
    .attr("height", 176);

这将图案的尺寸设置为16×11,将用于剪切包含的图像。然后将flags.png图像转换为正确的偏移(例如,美国为-128,-154),从而将美国国旗定位为根据需要显示。当然,这也适用于任何其他旗帜。

请查看以下代码片段以了解正常工作:

var svg = d3.select("#chartContainer")
  .append('svg')
    .attr("width", 400)
    .attr("height", 400)
  .append('g');

svg.append("pattern")
    .attr("id", "us")
    .attr("width", 16)
    .attr("height", 11)
  .append("image")
    .attr("xlink:href", "https://dl.dropboxusercontent.com/u/5258675/flags.png")
    .attr("transform", "translate(-128, -154)")
    .attr("width", 256)
    .attr("height", 176);

svg.append("rect")
    .attr("width", 16)
    .attr("height", 11)
    .attr("x", 50)
    .attr("y", 50)
    .attr("fill", "url(#us)");
<script src="https://d3js.org/d3.v4.js"></script>
<div id="chartContainer"></div>