voi*_*oid 2 javascript svg d3.js
我正在使用基于 D3.js 构建的 CodeFlower。我想将图像显示为背景而不是任意颜色,并且我使用 SVG Patterns 成功地做到了这一点。
// Enter any new nodes
this.node.enter().append('defs')
.append('pattern')
.attr('id', function(d) { return (d.id+"-icon-img");}) // just create a unique id (id comes from the json)
.attr('patternUnits', 'userSpaceOnUse')
.attr('width', 80)
.attr('height', 80)
.append("svg:image")
.attr("xlink:xlink:href", function(d) { return (d.icon);}) // "icon" is my image url. It comes from json too. The double xlink:xlink is a necessary hack (first "xlink:" is lost...).
.attr("x", 0)
.attr("y", 0)
.attr("height", 80)
.attr("width", 80)
.attr("preserveAspectRatio", "xMinYMin slice");
this.node.enter().append('svg:circle')
.attr("class", "node CodeFlowerNode")
.classed('directory', function(d) { return (d._children || d.children) ? 1 : 0; })
.attr("r", function(d) { return d.children ? 3.5 : Math.pow(d.size, 2/5) || 1; })
.style("fill", function(d) { return ("url(#"+d.id+"-icon-img)");})
/* .style("fill", function color(d) {
return "hsl(" + parseInt(360 / total * d.id, 10) + ",90%,70%)";
})*/
.call(this.force.drag)
.on("click", this.click.bind(this))
.on("mouseover", this.mouseover.bind(this))
.on("mouseout", this.mouseout.bind(this));
Run Code Online (Sandbox Code Playgroud)
我看到的问题是图像没有在圆圈中居中对齐,它是一种由 4 个图像组成的平铺布局。
我怎样才能使它的位置居中并很好地覆盖圆圈。
您需要改变定义模式的方式。您应该根据应用它的元素来定义它。所以,离开patternUnits时的默认objectBoundingBox,并设置width和height到1。
然后您还需要将 设置patternContentUnits为objectBoundingBox也,并给出<image>相同的大小(宽度和高度1)。
this.node.enter().append('defs')
.append('pattern')
.attr('id', function(d) { return (d.id+"-icon");})
.attr('width', 1)
.attr('height', 1)
.attr('patternContentUnits', 'objectBoundingBox')
.append("svg:image")
.attr("xlink:xlink:href", function(d) { return (d.icon);})
.attr("height", 1)
.attr("width", 1)
.attr("preserveAspectRatio", "xMinYMin slice");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3035 次 |
| 最近记录: |