引子
使用d3.js繪制了力布圖后,需要在circle
中繪制圖片,方法如下:
// 繪制圖片
drawPattern(gContainer) {
let that = this;
let gPattern = gContainer.append("g").attr("class", "g-pattern");
// 添加pattern
pattern = gPattern.selectAll("pattern").data(that.nodes, function(node) {
return "pattern" + node.id;
});
// 賦予寬高
pattern
.enter()
.append("pattern")
.attr("id", function(node) {
return "pattern" + node.id;
})
.attr("x", 0)
.attr("y", 0)
.attr("height", 64)
.attr("width", 64)
.append("svg:image");
// 插入圖片
pattern
.selectAll("image")
.data(that.nodes, function(node) {
return "pattern-image" + node.id;
})
.attr("xlink:href", function(node) {
return node.image;
})
.attr("x", 0)
.attr("y", 0)
.attr("height", function(node) {
return that.imageHeight;
})
.attr("width", function(node) {
return that.imageWidth
});
}
circle
中加入指向
circles.style('fill',function(node){ return "url(#" + "pattern" + node.id + ")"; })
實現后的:
發現一個問題就是當圖片寬高不一致的時候,會出現無法填充圓圈的問題
問題解決
給圖片加入preserveAspectRatio
的屬性后問題解決了~
... 省略代碼...
pattern
.selectAll("image")
.data(that.nodes, function(node) {
return "pattern-image" + node.id;
})
.attr("preserveAspectRatio","none")
.attr("xlink:href", function(node) {
return node.icon;
})
....省略代碼...
一臉懵逼嗎.gif
關於preserveAspectRatio
<image>
的控制圖片比例的屬性,指的是引用的圖像如何與參考視圖進行匹配,以及是否應該相對於當前用戶坐標系保留參考圖像的長寬比
它的值有2個 <align> <meetOrSlice>
<align>
<meetOrSlice>
是可選的,如果提供的話, 與
上面尼,我們就是希望圖片按照我們指定的寬高使得元素的邊界完全匹配視圖圓形,因此設置成"none"
參數說明源自:https://developer.mozilla.org/zh-CN/docs/Web/SVG/Attribute/preserveAspectRatio
該屬性可還和viewBox屬性聯用,關於該部分的說明,張鑫旭的這篇博客介紹的很全面:https://www.zhangxinxu.com/wordpress/2014/08/svg-viewport-viewbox-preserveaspectratio/