Unknown User
Unknown User

Reputation: 3668

d3 - draw lines n number of times

I have a vertical-line which is drawn using d3. Suppose I want to repeat the line for a several number of times like a bar code. How do I do it?

I know that it has to be done using for but i don't have any clue on how to do it.

Suggestions will be very much helpful.

FIDDLE

Here's the code:

var height = 500;
    var width = 500;

    var svgContianer = d3.select("body")
                        .append("svg")
                        .attr("width", width)
                        .attr("height", height)


    var line = svgContianer.append("line")
                            .attr("x1", 20)
                            .attr("x2", 20)
                            .attr("y1", 100)
                            .attr("y2", 0)
                            .attr("stroke", "#000")
                            .attr("stroke-width", 2)

Thanks in advance.

Upvotes: 0

Views: 1354

Answers (2)

musically_ut
musically_ut

Reputation: 34288

If you want to create a bar code, the D3 way to do it would be to bind each line (element) with its width (data) and then using D3's enter phase to construct them.

Also, for bar-codes, you would also want to turn shape-rendering to crispEdges.

Demo.

var height = 500;
var width = 500;

var svgContianer = d3.select("body")
    .append("svg")
    .attr("width", width)
    .attr("height", height)


var line = svgContianer.selectAll("line")
    .data([1, 2, 1, 3, 2, 1, 3, 2, 1, 3, 2, 4, 3, 1, 2, 2, 2, 1, 3, 2])
    .enter()
    .append("line")
    .attr("x1", function (d, i) {
      return 20 + 5 * i;
    })
    .attr("x2", function (d, i) {
      return 20 + 5 * i;
    })
    .attr("y1", 100)
    .attr("y2", 0)
    .attr("stroke", "#000")
    .attr("stroke-width", function (d) {
      return d;
    })

Upvotes: 2

Vikram Deshmukh
Vikram Deshmukh

Reputation: 15626

There are better options than using a for loop. But, in any case here you go

var height = 500;
var width = 500;
var count = 10, padding = 5;
var svgContianer = d3.select("body")
                        .append("svg")
                        .attr("width", width)
                        .attr("height", height)

for(var i = 0; i < count; ++i) {
    var line = svgContianer.append("line")
                            .attr("x1", padding*i)
                            .attr("x2", padding*i)
                            .attr("y1", 100)
                            .attr("y2", 0)
                            .attr("stroke", "#000")
                            .attr("stroke-width", 2)
}

Upvotes: 1

Related Questions