【问题标题】:D3js canvas and line are not visibleD3js 画布和线条不可见
【发布时间】:2016-10-25 06:46:13
【问题描述】:

我有以下代码应该在画布元素中显示淹没线。

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 还是其他东西(例如纯绘图到画布)?

非常感谢您的建议。

【问题讨论】:

  • canvas 不是基于 DOM 的东西。您可以通过 canvas API 获得一个画布上下文并在其上绘制线条。

标签: javascript html canvas d3.js svg


【解决方案1】:

CanvasSVG 完全不同。这不仅仅是在d3.select("body").append() 代码中将“svg”更改为“canvas”的问题。您应该研究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>

但是,当然,您不希望这有任何结果。

【讨论】:

    【解决方案2】:

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

    d3和canvas不一样。

    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>

    【讨论】:

      猜你喜欢
      • 2012-12-31
      • 1970-01-01
      • 1970-01-01
      • 2016-02-23
      • 1970-01-01
      • 1970-01-01
      • 2015-03-14
      • 1970-01-01
      • 2017-02-10
      相关资源
      最近更新 更多