2016-10-24 65 views
0

我有下面的代码应该在canvas元素中显示淹死的线条。D3js的画布和线条不可见

var initCanvas = function() { 

var episodeLengthInPixels = moment.duration(episodeLogLength).asSeconds() * episodeWidthMultiplication; 
console.log("Length of chart is "+episodeLengthInPixels +" px"); 

try { 
    canvas = d3.select("body").append("canvas") 
    .attr("width", 500) 
    .attr("height", canvasHeight) 
    .attr("class", canvasSelector); 


//Draw the Line 
    canvas.append("line")   // attach a line 
    .style("stroke", "black") // colour the line 
    .attr("x1", 0)  // x position of the first end of the line 
    .attr("x2", 500) 
    .attr("y1", waveHeight) 
    .attr("y2", waveHeight) ; 

} catch (e) { 
    console.error(e); 
} 
} 

问题是画布和线条在DOM模型中可用但不可见(不会抛出异常)。当我尝试使用SVG而不是画布时,一切正常。

如何使用D3.js库在画布上显示内容?我试图找到任何例子,但没有运气。我应该使用画布使用D3.js还是其他的东西(例如在画布中纯画图)?

非常感谢您的任何建议。

+1

画布是不是基于DOM的事情。您将获得一个画布上下文并通过画布API在其上绘制线条。 –

回答

2

CanvasSVG是有区别的。这不仅仅是在d3.select("body").append()代码中为“画布”更改“svg”的问题。你应该研究canvas documentationSVG documentation

此,例如,是如何绘制在canvas线:

var chart = d3.select("body").append("canvas") 
 
    .attr("width", 400) 
 
    .attr("height", 300); 
 

 
var context = chart.node().getContext("2d"); 
 

 
context.beginPath(); 
 
context.moveTo(0,100);//here you set the equiv. to X1 and Y1 in SVG 
 
context.lineTo(400,100);//here you set the equiv. to X2 and Y2 in SVG 
 
context.stroke();
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

另外,请记住,事实上,你看到一个给定的元素检查DOM没有按当这并不意味着元素会出现。你可以使这个非常简单的测试使用D3:

d3.select("body").append("div").append("charlesdarwin"); 

你会看到这个检查DOM:

<div> 
    <charlesdarwin></charlesdarwin> 
</div> 

但是,当然,你不会想到,这有什么结果。

0

这里是一个从这里采取的例子。 https://bocoup.com/weblog/d3js-and-canvas

d3和画布不一样。

var base = d3.select("#foo"); 
 
var chart = base.append("canvas") 
 
    .attr("width", 400) 
 
    .attr("height", 300); 
 

 
var context = chart.node().getContext("2d"); 
 
var data = [1,2,13,20,23]; 
 

 
var scale = d3.scale.linear() 
 
    .range([10, 390]) 
 
    .domain([1,23]); 
 

 
data.forEach(function(d, i) { 
 
    context.beginPath(); 
 
    context.rect(scale(d), 150, 10, 10); 
 
    context.fillStyle="red"; 
 
    context.fill(); 
 
    context.closePath(); 
 
}); 
 
// Your line here... 
 
context.beginPath(); 
 
context.moveTo(10,10); 
 
context.lineTo(40,60); // x2,y2 ... 
 
context.stroke(); 
 
context.closePath();
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script> 
 

 
<a href="https://bocoup.com/weblog/d3js-and-canvas">Examples here</a> 
 

 
<div id="foo"></div>