使用D3在鼠标位置绘制圆点onClick

时间:2022-11-20 18:27:26

I'm trying to work with D3 for a simple web app. I'm new to D3 (and web applications in general), but the current goal is to draw a circle wherever I click inside a single Div. I'm following the tutorial here to draw my circle. However, after adding this code in, I'm not getting a black circle to appear. I posted the code below... is there something I'm missing? (BTW, the console log is working perfectly)

我正在尝试使用D3来创建一个简单的Web应用程序。我是D3(以及一般的Web应用程序)的新手,但目前的目标是在单个Div内部点击的任意位置绘制一个圆圈。我在这里按照教程绘制我的圆圈。但是,在添加此代码后,我没有出现黑色圆圈。我在下面发布了代码......有什么我想念的吗? (顺便说一下,控制台日志工作正常)

html:

<!DOCTYPE html>
<html>
<head>
    <script src="https://d3js.org/d3.v3.min.js"></script>
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" href="../css/topo_creator.css" media="screen" />
    <script src="../javascript/graph.js" type="text/javascript"></script> 
</head>
<body>
    <div class="view_graph" id="graph" onclick="graphClicked(event);">

    </div>
</body>

javascript:

function graphClicked(event) {
var x = event.pageX;
var y = event.pageY;

var offsetX = document.getElementById('graph').offsetLeft;
var offsetY = document.getElementById('graph').offsetTop;

var divWidth = document.getElementById('graph').clientWidth;
var divHeight = document.getElementById('graph').clientHeight;

var svg = d3.select('graph').append('svg')
            .attr('width', divWidth)
            .attr('height', divHeight);

var circle = svg.append('circle')
                .attr('cx', (x - offsetX))
                .attr('cy', (y - offsetY))
                .attr('r', 20);

console.log('clicked: ' + (x - offsetX) + ' , ' + (y - offsetY));
}

1 个解决方案

#1


2  

You forgot the # to indicate this is an html id.

你忘了#表示这是一个HTML身份证。

var svg = d3.select('#graph').append('svg')
            .attr('width', divWidth)
            .attr('height', divHeight);

See here (http://codepen.io/f7o/pen/zBZBWY)

看这里(http://codepen.io/f7o/pen/zBZBWY)

#1


2  

You forgot the # to indicate this is an html id.

你忘了#表示这是一个HTML身份证。

var svg = d3.select('#graph').append('svg')
            .attr('width', divWidth)
            .attr('height', divHeight);

See here (http://codepen.io/f7o/pen/zBZBWY)

看这里(http://codepen.io/f7o/pen/zBZBWY)