我在使用RequireJS加載D3 v4.8和文字雲佈局組件(https://github.com/jasondavies/d3-cloud)時遇到問題。雖然D3.js和d3.layout.cloud.js都正在下載到瀏覽器,但正在拋出異常,表明d3.layout.cloud不是函數。使用RequireJS加載D3和Word Cloud佈局
這裏是我正在配置RequireJS:
require.config({
waitSeconds: 10,
baseUrl: './scripts',
paths: {
d3: 'd3.min',
jquery: 'jquery-2.1.0.min',
cloud: 'd3.layout.cloud'
},
shim: {
cloud: {
deps:['jquery', 'd3']
}
}
});
的代碼拋出異常該生產線是d3.layout.cloud()的大小([寬度,高度]),並且可以在被發現。下面的功能:
function wordCloud(selector) {
var width = $(selector).width();
var height = $(selector).height();
//var fill = d3.scale.category20();
//Construct the word cloud's SVG element
var svg = d3.select(selector).append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate("+ width/2 +","+ height/2 +")")
var fill = d3.scale.category20();
//Draw the word cloud
function draw(words) {
var cloud = svg.selectAll("g text")
.data(words, function(d) { return d.text; })
//Entering words
cloud.enter()
.append("text")
.style("font-family", "Impact")
.style("fill", function(d, i) { return fill(i); })
.attr("text-anchor", "middle")
.attr('font-size', 1)
.style("cursor", "hand")
.text(function(d) { return d.text; })
.on("click", function (d, i){
window.open("http://www.google.com/?q=" + d.text, "_blank");
});
//Entering and existing words
cloud
.transition()
.duration(600)
.style("font-size", function(d) { return d.size + "px"; })
.attr("transform", function(d) {
return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
})
.style("fill-opacity", 1);
//Exiting words
cloud.exit()
.transition()
.duration(200)
.style('fill-opacity', 1e-6)
.attr('font-size', 1)
.remove();
}
//Use the module pattern to encapsulate the visualisation code. We'll
// expose only the parts that need to be public.
return {
//Recompute the word cloud for a new set of words. This method will
// asycnhronously call draw when the layout has been computed.
//The outside world will need to call this function, so make it part
// of the wordCloud return value.
update: function(words) {
// min/max word size
var minSize = d3.min(words, function(d) { return d.size; });
var maxSize = d3.max(words, function(d) { return d.size; });
var textScale = d3.scale.linear()
.domain([minSize,maxSize])
.range([15,30]);
d3.layout.cloud().size([width, height])
.words(words.map(function(d) {
return {text: d.text, size: textScale(d.size) };
}))
.padding(5)
.rotate(function() { return ~~(Math.random() * 2) * 90; })
.font("Impact")
.fontSize(function(d) { return d.size; })
.on("end", draw)
.start();
}
}
}
謝謝@GerardoFurtado,我會盡快在D3 v3.x上運行我的一個例子。我會讓你知道它是怎麼回事......感謝關於賞金的建議。 – UncleZen
我認爲d3-cloud對d3v4的依賴並不存在問題。查看整個d3-cloud的源代碼[here](https://github.com/jasondavies/d3-cloud/blob/master/index.js),你可以看到唯一的依賴是'd3-dispatch',它我猜想加載就好了。我相信問題在於你試圖將它放入'd3.layout.cloud',因爲在d3v4中'd3.layout'是'undefined'。嘗試將所有對'd3.layout.cloud'的引用更改爲'd3.cloud'(即在require的配置和源代碼中)。 – meetamit
@UncleZen我刪除了我的評論,因爲d3-cloud與D3 v4.x協同工作。 –