我正在使用d3.js在(10,10)的左上角绘制一个矩形。
然后我通过translate(200, 200)
移动该矩形。
然后我附上一个on-mouseout事件,它只是打印出鼠标指针的坐标。令我惊讶的是,它报告的坐标表示矩形在翻译之前的边界。为什么???
如何让它报告实际的鼠标坐标,而不是矩形在翻译之前的位置?
以下是代码:
var myApp = angular.module('myApp', []);
myApp.controller('MyController', function() {
var self = this;
self.svgContainer = d3.select("#my_svg_widget");
var my_rect = self.svgContainer.append("rect")
.attr("x", 10)
.attr("y", 10)
.attr("width", 60)
.attr("height", 60);
my_rect.attr("transform", "translate(200, 200)");
my_rect.on("mouseover", function() {
var coordinates = [0, 0];
coordinates = d3.mouse(this);
var mouseX6 = Number(coordinates[0]);
var mouseY6 = Number(coordinates[1]);
console.log('mouseX6 = ', mouseX6, typeof mouseX6);
console.log('mouseY6 = ', mouseY6, typeof mouseY6);
}
);
}
);
这是输出:
mouseX6 = 13 number
mouseY6 = 9 number
以下是Plunker:https://plnkr.co/edit/VSTzUhehdsVLFgmZqzHi?p=preview
答案 0 :(得分:3)
d3.mouse - >找到当前鼠标事件相对于容器元素的x,y坐标。
试试这段代码:
var coordinates = d3.mouse(this);
var pt = self.svgContainer.node().createSVGPoint();
pt.x = coordinates[0];
pt.y = coordinates[1];
pt = pt.matrixTransform(my_rect.node().getCTM());
var mouseX6 = pt.x, mouseY6 = pt.y;
更新了plunker: 尝试点击矩形来测试新的位置计算。
var self = {};
self.svgContainer = d3.select("#my_svg_widget");
console.log("Hello!");
var my_rect = self.svgContainer.append("rect")
.attr("x", 10)
.attr("y", 10)
.attr("width", 60)
.attr("height", 60)
.attr("fill", "Pink")
.attr("stroke", "Blue")
.attr("stroke-width", 2);
my_rect.attr("transform", "translate(200, 200)");
my_rect.on("mouseover", function() {
console.log("\n\n\n================ MouseOver Rectangle ================");
var coordinates = [0, 0];
console.log("1");
coordinates = d3.mouse(this);
var pt = self.svgContainer.node().createSVGPoint();
pt.x = coordinates[0];
pt.y = coordinates[1];
pt = pt.matrixTransform(my_rect.node().getCTM());
//coordinates = d3.mouse(self.svgContainer);
console.log("2");
var mouseX6 = Number(coordinates[0]);
var mouseY6 = Number(coordinates[1]);
console.log('mouseX6 = ', mouseX6, typeof mouseX6);
console.log('mouseY6 = ', mouseY6, typeof mouseY6);
mouseX6 = pt.x;
mouseY6 = pt.y;
console.log('mouseX6 = ', mouseX6, typeof mouseX6);
console.log('mouseY6 = ', mouseY6, typeof mouseY6);
});
my_rect.on("click", function() {
console.log("\n\n\n================ Click on Rectangle ================");
var coordinates = d3.mouse(this);
var pt = self.svgContainer.node().createSVGPoint();
pt.x = coordinates[0];
pt.y = coordinates[1];
pt = pt.matrixTransform(my_rect.node().getCTM());
var mouseX6 = pt.x,
mouseY6 = pt.y;
self.svgContainer.append("circle").attr("cx", pt.x).attr("cy", pt.y).attr("r", 3);
console.log('mouseX6 = ', mouseX6, typeof mouseX6);
console.log('mouseY6 = ', mouseY6, typeof mouseY6);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<svg id="my_svg_widget" width="300" height="300" style="border-style:solid;border-color:purple;border-width: 2px;">
</svg>
答案 1 :(得分:0)
以下链接可帮助您了解d3中transforma的工作原理。