Skip to content

Instantly share code, notes, and snippets.

@mzechmeister
Last active December 7, 2022 17:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mzechmeister/c3f0557b0bb87f6b410d6d49e1124bda to your computer and use it in GitHub Desktop.
Save mzechmeister/c3f0557b0bb87f6b410d6d49e1124bda to your computer and use it in GitHub Desktop.
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<body>
<div id="myDiv" oncontextmenu="return false"></div>
<script>
var d3 = Plotly.d3,
N = 1000,
y = d3.range(N).map(d3.random.normal()),
data = [{y: y}]
layout = {title: 'Right-click-drag to zoom'}
Plotly.plot(myDiv, data, layout)
var zoomspeed = 1 / 20 // [zoomfac/px]
zoomfac = d => d<0 ? 1 - d*zoomspeed : 1 / (1 + d*zoomspeed)
function rubber_init(e) {
e.stopPropagation() // zoom bug (https://github.com/plotly/plotly.js/issues/5311), mousedown is attached to nsewdrag
var obj = e.currentTarget
xaxis = obj._fullLayout.xaxis
yaxis = obj._fullLayout.yaxis
X0 = e.clientX
Y0 = e.clientY
x0 = xaxis.p2r(X0-obj._fullLayout.margin.l-obj.getBoundingClientRect().left)
y0 = yaxis.p2r(Y0-obj._fullLayout.margin.t-obj.getBoundingClientRect().top)
rx0 = xaxis.range
ry0 = yaxis.range
obj.onmousemove = rubber_zoom
obj.onmouseup = function(e) {
obj.onmousemove = null
}
}
function rubber_zoom(e) {
xfac = zoomfac(e.clientX-X0)
yfac = zoomfac(-(e.clientY-Y0))
// new ranges
Rx0 = x0 - xfac * (x0-rx0[0])
Rx1 = x0 - xfac * (x0-rx0[1])
Ry0 = y0 - yfac * (y0-ry0[0])
Ry1 = y0 - yfac * (y0-ry0[1])
Plotly.relayout(e.currentTarget,
{'xaxis.range': [Rx0, Rx1],
'yaxis.range': [Ry0, Ry1]})
}
myDiv.addEventListener("mousedown", function(e) {
if (e.buttons == 2) rubber_init(e)
}, true) // true needed, otherwise the zoom bug (https://github.com/plotly/plotly.js/issues/5311) is not caught
</script>
</body>
@mzechmeister
Copy link
Author

mzechmeister commented May 9, 2022

Preview: https://gistpreview.github.io/?c3f0557b0bb87f6b410d6d49e1124bda
Developed for plotly/plotly.js#6176

Rev 3: Fix: Slightly wrong position of reference point. Refact: rubber_init function.
Rev 5: Better fix for right mouse zoom bug.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment