在 D3.js 中实时绘制线条 [英] Live drawing of a line in D3.js

查看:92
本文介绍了在 D3.js 中实时绘制线条的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始使用 D3.js,我想创建一些类似于我们在 Paint 中所做的画线.步骤应该是一样的:- 单击屏幕上的一个点- 拖动到目的地以创建一条线.

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?

谢谢.

推荐答案

这是一个简单的例子.另请参阅实时版本.

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);
}

我认为您正在寻找的部分在 mousemove 事件处理程序中,我们选择当前行并根据当前鼠标位置调整它的目标点.请注意,我们只在 mousedown 中启用 mousemove 以避免多余的处理.

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.

这篇关于在 D3.js 中实时绘制线条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆