Canvas无法识别手势:SvelteKit中svelte-gestures失效排查
问题:SvelteKit本地项目中svelte-gestures无法识别Canvas手势
我使用svelte-gestures库在Canvas上实现手势识别,在Svelte REPL(包括库开发者提供的示例和我自行创建的测试环境)中均能正常运行,但将代码迁移到SvelteKit本地项目后,Canvas元素完全无法识别手势。通过开发者工具观察到,Canvas被自动添加了额外样式:{ touch-action:none; user-select:none }。
测试拆解
为定位问题,我拆分场景逐一测试:
示例1:嵌套结构测试
最初怀疑是Canvas嵌套在div/section中导致问题,但测试后该场景无异常。
<section> <div> <canvas width={300} height={300} ></canvas> </div> </section> <style> canvas { border:solid; } </style>
示例2:基础手势测试
添加tap和swipe两种基础手势后,功能仍失效,此时Canvas自动添加的样式变为{ touch-action: auto },即便不是none也无法正常工作。
<script> import { swipe, tap } from 'svelte-gestures'; function tapHandler() { console.log("tap") // 无日志输出 } function swipeHandler(event) { console.log("swipe") // 无日志输出 } </script> <section> <div> <canvas width={300} height={300} use:swipe={{ timeframe: 300, minSwipeDistance: 60 }} on:swipe={swipeHandler} use:tap on:tap={tapHandler} ></canvas> </div> </section> <style> canvas { border:solid; } </style>
示例3:复合手势测试
使用简化后的原始代码,添加composedGesture避免移动端长按/下拉被识别为滚动,该代码在REPL中正常,但本地项目仍失效。
<script> import { swipe, tap, composedGesture, press, scroll, pan } from 'svelte-gestures'; function tapHandler() { console.log("tap") // 无日志输出 } function swipeHandler(event) { console.log("swipe") // 无日志输出 } // 阻止长按/下拉被识别为页面滚动 function scrollPan(register) { const pressFns = register(press, { triggerBeforeFinished: true, spread: 10, timeframe: 100, }); const scrollFns = register(scroll, { delay: 0 }); const panFns = register(pan, { delay: 0 }); return (activeEvents, event) => { pressFns.onMove(activeEvents, event) || event.pointerType !== 'touch' ? panFns.onMove(activeEvents, event) : scrollFns.onMove(activeEvents, event); }; }; </script> <section> <div> <canvas width={300} height={300} use:swipe={{ timeframe: 300, minSwipeDistance: 60 }} on:swipe={swipeHandler} use:tap on:tap={tapHandler} use:composedGesture={scrollPan} ></canvas> </div> </section> <style> canvas { border:solid; } </style>
已尝试的解决方法
查阅SvelteKit文档得知:“若使用SvelteKit,src文件夹中已有global.d.ts,只需在其后添加该行” /// <reference types="@sveltejs/kit" />。但我的项目中没有global.d.ts,只有app.d.ts,于是将该行添加到其中,但问题仍未解决。
内容的提问来源于stack exchange,提问作者louislugas
相关产品推荐
相关产品推荐

