如何使用nodejs,d3和jsdom修改基于svg的dom的内容?
问题描述:
我正在尝试使用nodejs,jsdom和d3 v4来组装和托管svg。 我写了一个updated version的this example,因为它不能正常工作。但是,我不得不手动设置关闭svg标签,因为我不知道如何使用d3在svg的主体内添加路径。如何使用nodejs,d3和jsdom修改基于svg的dom的内容?
如何使用d3在svg内部的例子中添加最后一个路径?
UPDATE 1
这从updated version部设法STRUCT的SVG的主要部分。一切都被追加后,第二部分试图unsucessfully添加路径数据,因为数据被追加超越收盘SVG标签:
var document = jsdom.jsdom();
var svg = d3.select(document.body)
svg.append('svg')
.attr('xmlns', 'http://www.w3.org/2000/svg')
.attr('xmlns:xlink', 'http://www.w3.org/1999/xlink')
.attr('width', width + pad.l + pad.r)
.attr('height', height + pad.t + pad.b)
.append('g')
.attr('transform', 'translate(' + pad.l + ',' + pad.t + ')')
.append('g')
.attr('class', 'x axis')
.call(xAxis)
.append('g')
.attr('class', 'y axis')
.call(yAxis)
.selectAll('.axis text')
.style('fill', '#888')
.style('font-family', 'Helvetica Neue')
.style('font-size', 11)
.selectAll('.axis line')
.style('stroke', '#eee')
.style('stroke-width', 1)
.selectAll('.domain')
.style('display', 'none')
svg.selectAll('path.samples')
.data([samples])
.enter()
.append('path')
.attr('class', 'samples')
.attr('d', line)
.style('fill', 'none')
.style('stroke', '#c00')
.style('stroke-width', 2)
答
你必须分开您的选择
var document = jsdom.jsdom();
var body = d3.select(document.body)
var svg = body .append('svg')
.attr('xmlns', 'http://www.w3.org/2000/svg')
.attr('xmlns:xlink', 'http://www.w3.org/1999/xlink')
.attr('width', width + pad.l + pad.r)
.attr('height', height + pad.t + pad.b)
// now we appending g element to the svg
var g = svg
.append('g')
.attr('transform', 'translate(' + pad.l + ',' + pad.t + ')')
//now we are appending container for x axis inside g
g.append('g')
.attr('class', 'x axis')
.call(xAxis)
//now we are appending container for y axis inside g
g
.append('g')
.attr('class', 'y axis')
.call(yAxis)
// now we are styling appended axis texts inside svg
svg.selectAll('.axis text')
.style('fill', '#888')
.style('font-family', 'Helvetica Neue')
.style('font-size', 11)
// now we are styling all ticks inside svg
svg.selectAll('.axis line')
.style('stroke', '#eee')
.style('stroke-width', 1)
// now we are styling both line inside svg again()
svg.selectAll('.domain')
.style('display', 'none')
// now we are appending paths to the svg
svg.selectAll('path.samples')
.data([samples]) // if samples is array and you want to bind each element to the path, then [ ] this brackets is redundant here
.enter()
.append('path')
.attr('class', 'samples')
.attr('d', line)
.style('fill', 'none')
.style('stroke', '#c00')
.style('stroke-width', 2)
我得到了它几乎工作,但现在xml头没有被服务器渲染(即只有g标签等进入响应)。我无法想象当我追加内容时文档的结构如何受到影响......这就是为什么我失去了正在发生的事情的原因...... – JPCF