先在html中新增一個要放入標籤雲的div:
再來在程式中引入d3和d3 cloud的函式庫 (在上列的d3 cloud連結中可以下載範例和函式庫):
最後撰寫我要的標籤雲部份:
(function() {
var fill = d3.scale.category20();
//要顯示於標籤雲的資料內容,為一個JSON物件的陣列
var data = [
{
text : "透視C語言",
size : 37,
url : 'http://www.tenlong.com.tw/items/9862769408?item_id=886353'
},
{
text : "超圖解 Arduino",
size : 35,
url : 'http://www.tenlong.com.tw/items/9863120847?item_id=577739'
},
{
text : "Linux Shell 程式設計",
size : 25,
url : 'http://www.tenlong.com.tw/items/986276970X?item_id=887065'
},
{
text : "無瑕的程式碼",
size : 40,
url : 'http://www.tenlong.com.tw/items/PG-001?item_id=884070'
},
{
text : "挑戰大數據",
size : 23,
url : 'http://www.tenlong.com.tw/items/9865764040?item_id=883951'
},
{
text : "Android 大螢幕手機",
size : 23,
url : 'http://www.tenlong.com.tw/items/9862018143?item_id=887255'
} ];
d3.layout.cloud().size([ 300, 300 ]).words(data).padding(3).rotate(
0).font('"微軟正黑體",Impact').fontSize(function(d) {
return d.size;
}).on("end", draw).start();
function draw(words) {
d3.select("#tag") //要插入標籤雲的tag id
.append("svg").attr("width", 300).attr("height", 300)
.append("g").attr("transform", "translate(150,150)") //這裡的值要對應到繪圖區域的寬、高的一半,針對不同的瀏覽器要設可以使用的值,如Chrome為-webkit-transform
.selectAll("text").data(words).enter().append("text")
.style("font-size", function(d) {
return d.size + "px";
})
.style("font-family", '"微軟正黑體",Impact')
.style("cursor", 'pointer')//當滑鼠移上去時,變換cursor
.style("fill", function(d, i) {
return fill(i);
}).attr("text-anchor", "middle")
.attr("transform",//跟上面的transform一樣,需依不同的瀏覽器設定對應的值
function(d) {
return "translate(" + [ d.x, d.y ] + ")rotate(" + d.rotate + ")";
})
.text(function(d) {
return d.text;
}).on('click', function(d) {//點按文字後,開啟超連結
window.open(d.url);
});
}
}());
最後的結果像這樣呈現:
上列範例原始碼可以在這裡下載。