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

隐身守侯 提交于 2019-12-29 03:33:12

问题


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.


回答1:


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.



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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!