Drawing Crosshairs with D3.js Using SVG Shapes


The JavaScript code below shows how to draw the crosshairs image above with D3.js using SVG circles and SVG lines.

JavaScript Code

var w = 600,
    h = 600,
    f = 'none',
    s = '#000000',
    so = 1,
    sw = '20px',
    svg = d3.select('#canvas').append('svg')
        .attr('width', w)
        .attr('height', h);

svg.append('circle')
    .attr('cx', w / 2)
    .attr('cy', h / 2)
    .attr('r', 240)
    .style('fill', f)
    .style('stroke', s)
    .style('stroke-opacity', so)
    .style('stroke-width', sw);

svg.append('circle')
    .attr('cx', w / 2)
    .attr('cy', h / 2)
    .attr('r', 60)
    .style('fill', f)
    .style('stroke', s)
    .style('stroke-opacity', so)
    .style('stroke-width', sw);

svg.append('line')
    .attr('x1', w / 2)
    .attr('y1', 0)
    .attr('x2', w / 2)
    .attr('y2', h)
    .style('stroke', s)
    .style('stroke-opacity', so)
    .style('stroke-width', sw);

svg.append('line')
    .attr('x1', 0)
    .attr('y1', h / 2)
    .attr('x2', w)
    .attr('y2', h / 2)
    .style('stroke', s)
    .style('stroke-opacity', so)
    .style('stroke-width', sw);

This post was written by Ramiro Gómez (@yaph) and published on . Subscribe to the Geeksta RSS feed to be informed about new posts.

Tags: d3js svg code

Disclosure: External links on this website may contain affiliate IDs, which means that I earn a commission if you make a purchase using these links. This allows me to offer hopefully valuable content for free while keeping this website sustainable. For more information, please see the disclosure section on the about page.