gpt4 book ai didi

node.js - 如何使用nodejs、d3和jsdom修改基于svg的dom的内容?

转载 作者:太空宇宙 更新时间:2023-11-04 02:02:40 24 4
gpt4 key购买 nike

我正在尝试使用nodejs、jsdom 和 d3 v4 组装和托管 svg。我写了一个updated versionthis example因为它没有按原样工作。但是,我必须手动设置结束 svg 标签,因为我不知道如何使用 d3 在 svg 主体内添加路径。

如何使用 d3 在 svg 内的示例中附加最后一个路径?

更新1

此部分来自 updated version设法构建 svg 的主要部分。附加所有内容后,第二部分尝试添加路径数据失败,因为数据附加到结束 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)

关于node.js - 如何使用nodejs、d3和jsdom修改基于svg的dom的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45433404/

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