简体   繁体   中英

Accessing array elements in d3.js

I want the user to be able to draw a line on an SVG canvas. At first, a "rough path" consisting of 1px by 1px rectangles is shown, then when the user releases the mouse, the line he traced is converted into a SVG <path> . This is the code that creates the rectangles:

var svg = d3.select('#svg-overlay'); //SVG Canvas
var roughPath = [];
( ... )
var tx = Math.round(e.pageX - offset.left);
var ty = Math.round(e.pageY - offset.top);

roughPath.push(svg.append('rect')
    .attr('width', 1)
    .attr('height', 1)
    .attr('x', tx)
    .attr('y', ty)
    .attr('fill', 'white'));

After the path has been drawn and converted into <path> , I want to be able to remove all the rectangles stored in roughPath . However, I can't figure out how to reach the elements inside that array. d3.select(roughPath) didn't work, neither did d3.select(roughPath).selectAll('rect') , nor roughPath.forEach(...) . Could someone pitch in a suggestion how I could reach d3 elements stored within an array, or at least how I could remove all elements within roughPath ?

Generally speaking, you shouldn't need to hold on to additional references to selections in your own structures (such as your roughPath array). Instead, think of the DOM as a collection of nodes (rects, in your case) that you can query using selectors.

If you add a class to the nodes you create on your rough path you can use that to query the group of nodes:

svg.append('rect')
    .attr('class', 'roughpath')
    .attr('width', 1)
    .attr('height', 1)
    .attr('x', tx)
    .attr('y', ty)
    .attr('fill', 'white');

Later, when you want to delete the nodes you can simply do:

svg.selectAll('rect.roughpath').remove();

Scott's answer is the most idiomatic way of doing what you're trying. If you really want to store the references in an array though, removing them is pretty simple:

roughPath.forEach(function(d){ d.remove(); })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM