有没有人对d3.js v3有过任何经验?
我试图通过html5画布上的3个点绘制线条而不是svg在它上面没有取得多大成功。据我所知,在svg中绘制图形的轴更容易。我需要绘制的点数简直压倒了DOM。
我查看了Canvas并行图here,但它太复杂了,无法满足我的需求。
<div id="line"></div>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script type="text/javascript">
var margin = {top: 20, right: 20, bottom: 20, left: 40},
w = 960 - margin.left - margin.right,
h = 500 - margin.top - margin.bottom;
var canvas = d3.select("#line").append("canvas")
.attr("width", w + margin.left + margin.right)
.attr("height", h + margin.top + margin.bottom)
.node().getContext('2d');
// using d3.canvas
var data = d3.range(3).map(function(){return Math.random()*10})
var line = d3.canvas.line();
d3.select('canvas').call(line, data);
</script>
我已经绘制了一条带有一些小变化的线:
添加:
<script src="./d3-canvas/d3.canvas.0.1.0.js" charset="utf-8"></script>
var data = [[0, 0], [10, 200]], line;
var margin = {top: 20, right: 20, bottom: 20, left: 40},
w = 960 - margin.left - margin.right,
h = 500 - margin.top - margin.bottom;
var canvas = d3.select("#line").append("canvas")
.attr("width", w + margin.left + margin.right)
.attr("height", h + margin.top + margin.bottom);
line = d3.canvas.line();
d3.select('canvas').call(line, data);
然而,这与我所链接的样本的表现有所不同。
答案 0 :(得分:2)
这是一个有点老问题。但是没有人回答,我也有同样的问题。所以一旦我弄清楚了,我决定在这里发帖。
bostock的例子就在这里。但是它使用的是早期的alpha版本4.这是我使用当前版本4的简单示例。
const Width = 300;
const Height = 200;
const margin = {top: 20, right: 20, bottom: 30, left: 40};
const width = Width - margin.right - margin.left;
const height= Height - margin.top - margin.bottom;
const xScale = d3.scaleLinear().rangeRound([0, width]);
const yScale = d3.scaleLinear().rangeRound([height, 0]);
const xAxis = d3.axisBottom(xScale);
const yAxis = d3.axisLeft( yScale);
const canvas = d3.select("canvas").attr("width", Width).attr("height", Height);
const context = canvas.node().getContext('2d');
context.translate(margin.left, margin.top);
const line = d3.line()
.x(d => xScale(d[0]))
.y(d => yScale(d[1]))
.context(context);
const data = [[0, 0], [10, 200], [20, 100]];
const xExtent = d3.extent(data, d => d[0]);
const yExtent = d3.extent(data, d => d[1]);
xScale.domain(xExtent);
yScale.domain(yExtent);
context.clearRect(0, 0, width, height);
context.beginPath();
line(data);
context.lineWidth = 1;
context.opacity = 0.7;
context.strokeStyle = "steelblue";
context.stroke();
context.closePath();