我最近想这样做,并在这里问了一个问题。我被指向phantomJS。使用 PhantomJS,我创建了一个 JS -
svggen.js:
var page = require('webpage').create(),
url = 'http://www.example.com/wordcloud.html';
page.open(url, function (status) {
if (status !== 'success') {
console.log('Unable to access network');
} else {
var svgData = page.evaluate(function(s){
var serializer = new XMLSerializer();
var element = document.getElementById("svg1");
return serializer.serializeToString(element);
});
console.log("<?xml version=\"1.0\"?>"+svgData);
}
phantom.exit();
});
wordcloud.html:
<!DOCTYPE html>
<meta charset="utf-8">
<body>
<script src="d3.min.js"></script>
<script src="d3.layout.cloud.js"></script>
<script>
var fill = d3.scale.category20();
d3.layout.cloud().size([500, 800])
.words([
"Hello", "world", "normally", "you", "want", "more", "words",
"than", "this"].map(function(d) {
return {text: d, size: 10 + Math.random() * 90};
}))
.padding(5)
.rotate(function() { return ~~(Math.random() * 2) * 90; })
.font("Impact")
.fontSize(function(d) { return d.size; })
.on("end", draw)
.start();
function draw(words) {
d3.select("body").append("svg")
.attr("width", 500)
.attr("height", 800)
.attr("id","svg1")
.attr("xmlns","http://www.w3.org/2000/svg")
.attr("xmlns:xlink","http://www.w3.org/1999/xlink")
.append("g")
.attr("transform", "translate(150,150)")
.selectAll("text")
.data(words)
.enter().append("text")
.style("font-size", function(d) { return d.size + "px"; })
.style("font-family", "Impact")
.style("fill", function(d, i) { return fill(i); })
.attr("text-anchor", "middle")
.attr("transform", function(d) {
return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
})
.text(function(d) { return d.text; });
}
</script>
</body></html>
然后我跑
phantomjs svggen.js > svgFile.svg
生成的 svgFile.svg 是一个独立的 SVG 文件。对于 d3cloud 检查这个。