Draw points

by jtr13

HTML

<h3 id="info">Click and drag to add points.</h3>
<h3 id="num">Number of points: 0</h3>
<button onclick="restart()">Restart</button>
<p></p>
<div id="plot"></div>

<script src="https://d3js.org/d3.v7.js"></script>

JavaScript

// width and height
  const w = 400;
  const h = 350;

  // create scale functions
  const xScale = d3.scaleLinear()
    .domain([0, 4])
    .range([0, w]);

  const yScale = d3.scaleLinear()
    .domain([0, 4])
    .range([h, 0]);

  // define X axis

  const svg = d3.select("div#plot")
    .append("svg")
    .attr("width", w)
    .attr("height", h);
    
  svg.append("rect")
    .attr("x", "0")
    .attr("y", "0")
    .attr("width", w)
    .attr("height", h)
    .attr("fill", "lightblue");

// add points

// https://stackoverflow.com/questions/18273884/live-drawing-of-a-line-in-d3-js

svg.on("mousedown", mousedown)
  .on("mouseup", mouseup);

// ############ MOUSEDOWN ###############

function mousedown() {
    const new_x = xScale.invert(d3.pointer(event)[0]);
	  const new_y = yScale.invert(d3.pointer(event)[1]);
    svg.append("circle")
        .data([{x: new_x, y: new_y}])
        .attr("cx", d => xScale(d.x))
        .attr("cy", d => yScale(d.y))
        .attr("r", "3");
    d3.select("h3#num").text("Number of points:" + d3.selectAll("circle").data().length);

    svg.on("mousemove", mousemove);
}

// ############ MOUSEMOVE ###############

function mousemove() {
    const new_x = xScale.invert(d3.pointer(event)[0]);
	  const new_y = yScale.invert(d3.pointer(event)[1]);
    svg.append("circle")
        .data([{x: new_x, y: new_y}])
        .attr("cx", d => xScale(d.x))
        .attr("cy", d => yScale(d.y))
        .attr("r", "3");
    d3.select("h3#num").text("Number of points:" + d3.selectAll("circle").data().length);    
}

// ############ MOUSEUP ###############

function mouseup() {
    svg.on("mousemove", null);
  }


function restart() {
  d3.selectAll("circle").remove();
  d3.select("h3#num").text("Number of points: 0")
}