|
| 1 | +import type { TPointerEventInfo, Canvas, TMat2D } from 'fabric'; |
| 2 | +import type { MakeMouseWheelProps } from './typedefs'; |
| 3 | + |
| 4 | +export const makeMouseWheel = |
| 5 | + (canvas: Canvas, props: Partial<MakeMouseWheelProps> = {}) => |
| 6 | + (options: TPointerEventInfo<WheelEvent>) => { |
| 7 | + const e = options.e; |
| 8 | + if (e.target == canvas.upperCanvasEl) e.preventDefault(); |
| 9 | + const { min, max, tSpeed = 0.99, mSpeed = 0.998, pSpeed = 1 } = props; |
| 10 | + |
| 11 | + /** Is it touchpad zoom? */ |
| 12 | + const isTouchScale = Math.floor(e.deltaY) != Math.ceil(e.deltaY); |
| 13 | + // Touchpad zooming, Mac's touchpad automatically sets e.ctrlKey to true |
| 14 | + if (e.ctrlKey || e.metaKey) { |
| 15 | + // Mouse and touchpad speed separate |
| 16 | + const speed = isTouchScale ? tSpeed : mSpeed; |
| 17 | + let zoom = canvas.getZoom(); |
| 18 | + zoom *= speed ** e.deltaY; |
| 19 | + if (max != undefined && zoom > max) zoom = max; |
| 20 | + if (min != undefined && zoom < min) zoom = min; |
| 21 | + |
| 22 | + canvas.zoomToPoint(options.viewportPoint, zoom); |
| 23 | + canvas.requestRenderAll(); |
| 24 | + return; |
| 25 | + } |
| 26 | + |
| 27 | + const vpt = canvas.viewportTransform.slice(0) as TMat2D; |
| 28 | + let { deltaX, deltaY } = e; |
| 29 | + // Hold down Shift and scroll the mouse to indicate horizontal scrolling |
| 30 | + if (e.shiftKey && deltaX == 0) { |
| 31 | + deltaX = deltaY; |
| 32 | + deltaY = 0; |
| 33 | + } |
| 34 | + vpt[4] -= deltaX * pSpeed; |
| 35 | + vpt[5] -= deltaY * pSpeed; |
| 36 | + canvas.setViewportTransform(vpt); |
| 37 | + canvas.requestRenderAll(); |
| 38 | + }; |
0 commit comments