gpt4 book ai didi

javascript - D3js Canvas 和线条不可见

转载 作者:行者123 更新时间:2023-12-02 14:03:23 26 4
gpt4 key购买 nike

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

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);
}
}

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

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

非常感谢您的建议。

最佳答案

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>

但是,当然,您不会期望这会产生任何结果。

关于javascript - D3js Canvas 和线条不可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40221656/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com