这里是我同时使用触摸屏或鼠标事件X如何固定,Y通过包裹事件屏幕坐标为优良D3例如上述坐标以更“通用”的x,y的对象。
(大概D3具有读,找出类似的处理这两种类型的事件的东西,但很多..)
//Get an class of {points: [{x, y},], type: event.type} clicked or touched
function getEventPoints(event)
{
var retval = {point: [], type: event.type};
//Get x,y of mouse point or touch event
if (event.type.startsWith("touch")) {
//Return x,y of one or more touches
//Note 'changedTouches' has missing iterators and can not be iterated with forEach
for (var i = 0; i < event.changedTouches.length; i++) {
var touch = event.changedTouches.item(i);
retval.point.push({ x: touch.clientX, y: touch.clientY })
}
}
else if (event.type.startsWith("mouse")) {
//Return x,y of mouse event
retval.point.push({ x: event.layerX, y: event.layerY })
}
return retval;
}
..这里是我会怎么用它在上面的例子D3存储最初的抓点Y.并且适用于鼠标和触摸。
检查Fiddle
在这里,我是如何解决这个问题,使用D3和想要拖动移动或触摸屏的文档。不知何故,d3事件订阅的所有图表区域事件已经被阻止冒泡DOM。
无法弄清楚,如果D3可以被配置成自动传递画布事件,不接触他们。所以在一次抗议中,我刚刚取消了d3,因为除了订阅活动之外,它并没有太多涉及。
并非是一个Javascript高手,这是一些有趣的代码,订阅事件的老路上。为了防止拖动屏幕上的图表触摸,只有当一个图表点grabed每个处理程序只需要回归真和event.preventDefault()被称为该事件保持你的自我。
//ChartJs event handler attaching events to chart canvas
const chartEventHandler = {
//Call init with a ChartJs Chart instance to apply mouse and touch events to its canvas.
init(chartInstance) {
//Event handler for event types subscribed
var evtHandler =
function myeventHandler(evt) {
var cancel = false;
switch (evt.type) {
case "mousedown":
case "touchstart":
cancel = beginDrag(evt);
break;
case "mousemove":
case "touchmove":
cancel = duringDrag(evt);
break;
case "mouseup":
case "touchend":
cancel = endDrag(evt);
break;
default:
//handleDefault(evt);
}
if (cancel) {
//Prevent the event e from bubbling up the DOM
if (evt.cancelable) {
if (evt.preventDefault) {
evt.preventDefault();
}
if (evt.cancelBubble != null) {
evt.cancelBubble = true;
}
}
}
};
//Events to subscribe to
var events = ['mousedown', 'touchstart', 'mousemove', 'touchmove', 'mouseup', 'touchend'];
//Subscribe events
events.forEach(function (evtName) {
chartInstance.canvas.addEventListener(evtName, evtHandler);
});
}
};
处理机上述启动这样与现有chart.js之对象:
chartEventHandler.init(chartAcTune);
的beginDrag(EVT),duringDrag(EVT)和endDrag(EVT)具有与上面d3例子相同的基本功能。当想要使用该事件并且不将它放在文档平移和类似的位置时,只返回true。
使用触摸屏在此尝试Fiddle。除非您接近选择图表点,否则图表的其余部分对触摸/鼠标事件是透明的,并允许平移页面。
y方向上存在初始小抓取偏移错误,并受浏览器窗口滚动位置的影响。 – flodis
解决方案。如果我使用:_chartInstance.scales [scale] .getValueForPixel(** e.layerY **)_,则Y坐标将补偿图表滚动位置。 – flodis
以下是我对第二个“旧”数据系列拒绝编辑和新值在整数步骤0..100中更改的图表的贡献。小提琴在这里:[小提琴](https://jsfiddle.net/flodis/3btgtptb/) – flodis