几个星期以来,我有点不知所措,试图让一个mousemove
事件在一组分层的画布上工作。按照之前文章中的建议,我确认事件只有在z-index
目标层位于顶部时才会正确触发(如这个简单的小提琴所示):
但是,在我正在使用的扩展代码(d3 parcoords)中,尽管具有与上面相同的 HTML 结构,但我无法在顶部的平行坐标图中为画布触发事件。
此块显示了扩展版本,以及即使目标分层画布具有最大z-index
的事件(尽管该事件在图表下方的简单画布中运行良好),事件如何不起作用。我尝试从 parcoords 文件中制作一个最小的示例,但考虑到互连功能的数量,我无法获得一个有用且有效的版本。
我希望知道原始 parcoords 代码的人能够澄清图表的画布是如何组织的,以及是否有特定的东西可能导致mousemove
事件无法工作。或者,也许一些有经验的眼睛可能会发现我在我发布的示例中遗漏的东西。非常感谢任何提示!
从生成画布的 d3.parcoords.js 中提取代码:
var pc = function(selection) {
selection = pc.selection = d3.select(selection);
__.width = selection[0][0].clientWidth;
__.height = selection[0][0].clientHeight;
// canvas data layers
["marks", "foreground", "brushed", "highlight", "clickable_colors"].forEach(function(layer, i) {
canvas[layer] = selection
.append("canvas")
.attr({
id: layer, //added an id for easier selecting for mouse event
class: layer,
style: "position:absolute;z-index: " + i
})[0][0];
ctx[layer] = canvas[layer].getContext("2d");
});
// svg tick and brush layers
pc.svg = selection
.append("svg")
.attr("width", __.width)
.attr("height", __.height)
.style("font", "14px sans-serif")
.style("position", "absolute")
.append("svg:g")
.attr("transform", "translate(" + __.margin.left + "," + __.margin.top + ")");
return pc;
};
用于绘制正方形和设置 mousemove 事件的函数:
//This custom function returns polyline ID on click, based on its HEX color in the hidden canvas "clickable_colors"
//Loosely based on http://jsfiddle.net/DV9Bw/1/ and https://stackoverflow.com/questions/6735470/get-pixel-color-from-canvas-on-mouseover
function getPolylineID() {
function findPos(obj) {
var curleft = 0, curtop = 0;
if (obj.offsetParent) {
do {
curleft += obj.offsetLeft;
curtop += obj.offsetTop;
} while (obj = obj.offsetParent);
return { x: curleft, y: curtop };
}
return undefined;
}
function rgbToHex(r, g, b) {
if (r > 255 || g > 255 || b > 255)
throw "Invalid color component";
return ((r << 16) | (g << 8) | b).toString(16);
}
// set up some squares
var my_clickable_canvas = document.getElementById('clickable_colors');
var context = my_clickable_canvas.getContext('2d');
context.fillStyle = "rgb(255,0,0)";
context.fillRect(0, 0, 50, 50);
context.fillStyle = "rgb(0,0,255)";
context.fillRect(55, 0, 50, 50);
$("#clickable_colors").mousemove(function(e) {
//$(document).mousemove(function(e) {
//debugger;
var pos = findPos(this);
var x = e.pageX - pos.x;
//console.log(x)
var y = e.pageY - pos.y;
var coord = "x=" + x + ", y=" + y;
var c = this.getContext('2d');
var p = c.getImageData(x, y, 1, 1).data;
var hex = "#" + ("000000" + rgbToHex(p[0], p[1], p[2])).slice(-6);
$('#status').html(coord + "<br>" + hex);
console.log("Polyline's hex:" + hex)
});
}