Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Live drawing of a line in D3.js [closed]

I'm just started with D3.js, and I want to create something like what we do in Paint to draw a line. The steps are should be the same: - Click on a point on the screen - Drag to the destination to create a line.

What I'm having troubles now is when you drag your mouse to the destination, the line should move according to your mouse. How can I do that?

Thanks.

like image 445
wayne Avatar asked Aug 16 '13 12:08

wayne


People also ask

How do you draw a horizontal line in D3 JS?

var st=line[v]; var x=v+1; var end=line[x]; var mean_value = meanArr[v]; svg. append("line") . attr("class", "mean-line") . attr({ x1: st, y1: y(mean_value), x2: end, y2: y(mean_value) });

Does D3 js use canvas?

js with canvas. There are three common ways D3 users render to canvas. You could use D3. js entirely for its functional purpose – to transform data that you can then position onto your canvas as you see fit.

What is the correct syntax to draw a circle in D3?

var circle = d3. selectAll("circle"); With a selection, we can make various changes to selected elements.


1 Answers

Here's a simple example. Also see live version.

var line;

var vis = d3.select("body").append("svg")
    .attr("width", 600)
    .attr("height", 400)
    .on("mousedown", mousedown)
    .on("mouseup", mouseup);

function mousedown() {
    var m = d3.mouse(this);
    line = vis.append("line")
        .attr("x1", m[0])
        .attr("y1", m[1])
        .attr("x2", m[0])
        .attr("y2", m[1]);

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

function mousemove() {
    var m = d3.mouse(this);
    line.attr("x2", m[0])
        .attr("y2", m[1]);
}

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

I think the part you're looking for is in the mousemove event handler where we select the current line and adjust it's destination point based on the current mouse location. Note that we only enable mousemove in mousedown to avoid superfluous processing.

like image 196
Yony Avatar answered Oct 05 '22 16:10

Yony