0
我试图通过d3.js将图表绘制到HTML5画布上。d3 JS动态画布
我下面就如何从这里做一个例子: http://bocoup.com/weblog/d3js-and-canvas/
我定义我onLoad
功能如下:
var jsonData = [1, 5, 6, 7, 9, 3, 10];
// add a Canvas element to our chart element
// choosing canvas so we can have animations should we decide to
var canvasElement = d3.select("#chart")
.append("canvas")
.attr("width", 800)
.attr("height", 575);
// virtual container for our circles
var inMem =document.createElement("customCircle");
var circleContainer = d3.select(inMem);
// make the circles for each of the categories
makeCircles(jsonData, circleContainer);
drawCircles(canvasElement, circleContainer);
});
而且makeCircles
和drawCircles
被定义为如下:
function makeCircles(data, circleContainer) {
var databind =circleContainer.selectAll("customCircle.circle")
.data(data);
databind.enter()
.append("customCircle")
.classed("circle", true)
.attr("x", (Math.random() * 800))
.attr("y", function(d) { return d; })
.attr("fillStyle", "#5cb85c");
}
function drawCircles(element, dataContainer) {
console.log(dataContainer);
var graphicsContext = element.node().getContext("2d");
graphicsContext.fillStyle = "#fff";
graphicsContext.rect(0, 0, 800, 575);
graphicsContext.fill();
var elements = dataContainer.selectAll("customCircle.circle");
elements.each(function(d) {
var node = d3.select(this);
graphicsContext.beginPath();
graphicsContext.fillStyle = node.attr("fillStyle");
graphicsContext.arc(node.attr("x"), node.attr("y"), node.attr("size"), 0, (2 * Math.PI));
graphicsContext.fill();
graphicsContext.closePath();
});
我似乎无法得到任何东西显示在实际的画布本身虽然,它只是空的。我怀疑dataContainer.selectAll("customCircle.circle")
行,因为我的代码永远不会进入每个循环(因此永远不会绘制)。我不明白为什么它不会;所有的自定义元素存在,当我通过console.log
检查它。
这里的附带的jsfiddle:http://jsfiddle.net/37871qu4/
非常感谢!你是正确的,我的“大小”属性没有分配,所以一切都设置为零。 – docaholic 2015-04-07 23:53:24