2016-10-24 132 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>