【发布时间】:2017-08-30 19:16:50
【问题描述】:
当鼠标滚轮滚动时,如何保证图表线的画布可以随鼠标位置放大和缩小?
在我的图表线画布中,我没有使用 chart.js 或 d3.js 或其他库。我希望它可以围绕鼠标位置进行放大和缩小,但值会随着放大和缩小而变化。如何确保中心点 - 鼠标位置 - 不受坐标系变化的影响。
【问题讨论】:
-
您是否使用
transform: scale()进行放大和缩小?
当鼠标滚轮滚动时,如何保证图表线的画布可以随鼠标位置放大和缩小?
在我的图表线画布中,我没有使用 chart.js 或 d3.js 或其他库。我希望它可以围绕鼠标位置进行放大和缩小,但值会随着放大和缩小而变化。如何确保中心点 - 鼠标位置 - 不受坐标系变化的影响。
【问题讨论】:
transform: scale() 进行放大和缩小?
如果您使用 CSS transform 属性 scale(),那么您可以设置另一个名为 transform-origin 的规则。如果在应用scale() 之前将其设置为屏幕中心,则页面将正确放大。
// performs the change of origin and scales the body element
zoom(scale, mouse) {
return $('body').css('transformOrigin', getMouse(mouse))
.css('transform', 'scale('+scale+')');
}
// returns a string of the current center of screen
getMouse() {
let midX = window.innerWidth / 2;
let midY = window.innerHeight / 2;
let x = $('body').css('left').split('p')[0];
let y = $('body').css('top').split('p')[0];
return String(midX - x + 'px ') + String(midY - y + 'px');
}
然后就可以用bind()方法实现滚动激活了:
let scale = 1;
let scrollFactor = -0.1;
$(window).bind('wheel mousewheel', function(e){
let scroll = e.originalEvent.deltaY;
let sign = Math.sign(scroll);
let newScale = Math.round((scale + scrollFactor * sign)*100)/100;
// you could set an if statement here before calling zoom() to
// set a lower and higher zoom limit
zoom(newScale, [e.pageX, e.pageY]);
});
【讨论】: