在回放时还原移动端触摸轨迹
解读
面试官问“在回放时还原移动端触摸轨迹”,并不是让你手写一个完整的录屏工具,而是考察三件事:
- 你是否知道移动端事件模型与 PC 端的差异;
- 你是否能把“采集—存储—回放”三个环节拆成可工程化的步骤,并给出性能与精度可权衡的方案;
- 你是否能在纯前端范围内(不借助原生插件)用最低成本落地,同时兼顾微信小程序、H5、React/Vue 项目的中国主流场景。
一句话:让面试官看到你能“低成本埋点、高精度还原、可插拔集成”。
知识点
-
事件层
- touchstart / touchmove / touchend 的事件对象结构(touches、changedTouches、targetTouches)
- 被动监听器
{passive: false}与80ms 延迟问题 - 防止系统默认行为
e.preventDefault()的微信内置浏览器白名单限制
-
采集层
- 时间戳
performance.now()与Date.now()的高精度差异 - 坐标系:clientX/Y、pageX/Y、getBoundingClientRect 的缩放补偿
- 采样策略:节流(throttle)+ 抽稀(Douglas-Peucker) 降低 60% 体积,仍保证 1 px 精度
- 时间戳
-
存储层
- 体积控制:单条轨迹 30 s 原始数据 ≈ 300 KB,gzip 后 40 KB;可接受
- 敏感合规:采集前必须弹窗授权(《个人信息保护法》第 13 条),且不上传密码框坐标
-
回放层
- 用
requestAnimationFrame按记录时的时间差逐帧绘制,避免setInterval掉帧 - 绘制方案:
– SVG 路径动画:<path>+stroke-dasharraytrick,零布局抖动
– Canvas 绘制:离屏 canvas +drawImage合成,不触发 DOM reflow,适合长页面 - 多端适配:
– H5 内嵌微信时,需把坐标乘以window.devicePixelRatio并抵消微信自动缩放
– 小程序端用cover-view做轨迹层,避开原生组件遮挡
- 用
-
工程化
- 把采集与回放封装成两个独立 Class,对外只暴露
startRecord()/play()/export()三个 API,方便在 Vue3setup()或 ReactuseEffect中即插即用 - 单元测试:用
@vue/test-utils触发TouchEvent构造器,断言回放终点坐标误差 < 0.5 px
- 把采集与回放封装成两个独立 Class,对外只暴露
答案
我给出一个可直接落地的 MVP 代码骨架,全部使用国内浏览器兼容的 API,不依赖任何第三方库,体积 < 3 KB(gzip)。
- 采集器(TouchRecorder)
class TouchRecorder {
constructor() {
this._轨迹 = []; // 最终导出数组
this._正在录 = false;
this._起时 = 0;
}
start() {
this._轨迹 = [];
this._正在录 = true;
this._起时 = performance.now();
document.addEventListener('touchstart', this._h, {passive: false});
document.addEventListener('touchmove', this._h, {passive: false});
document.addEventListener('touchend', this._h, {passive: false});
}
stop() {
this._正在录 = false;
['touchstart','touchmove','touchend']
.forEach(e => document.removeEventListener(e, this._h));
return this._抽稀(this._轨迹);
}
_h = (e) => {
if (!this._正在录) return;
e.preventDefault(); // 阻止滚动,提升精度
const [t] = e.changedTouches;
this._轨迹.push({
t: performance.now() - this._起时,
x: t.pageX,
y: t.pageY,
type: e.type
});
}
_抽稀(arr) { // Douglas-Peucker 简化
if (arr.length < 3) return arr;
const res = [arr[0]];
for (let i = 1; i < arr.length - 1; i++) {
const dx = arr[i].x - res[res.length - 1].x;
const dy = arr[i].y - res[res.length - 1].y;
if (Math.hypot(dx, dy) > 1) res.push(arr[i]); // 1 px 阈值
}
res.push(arr[arr.length - 1]);
return res;
}
}
- 回放器(TouchPlayer)
class TouchPlayer {
constructor(canvas) {
this.canvas = canvas;
this.ctx = canvas.getContext('2d');
this.dpr = window.devicePixelRatio || 1;
const {width, height} = canvas.getBoundingClientRect();
canvas.width = width * this.dpr;
canvas.height = height * this.dpr;
this.ctx.scale(this.dpr, this.dpr);
}
play(data) {
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.ctx.strokeStyle = '#ff4d4f';
this.ctx.lineWidth = 2;
this.ctx.beginPath();
let idx = 0;
const start = performance.now();
const tick = () => {
const now = performance.now() - start;
while (idx < data.length && data[idx].t <= now) {
const {x, y} = data[idx];
idx === 0 ? this.ctx.moveTo(x, y) : this.ctx.lineTo(x, y);
idx++;
}
this.ctx.stroke();
if (idx < data.length) {
requestAnimationFrame(tick);
}
};
tick();
}
}
- 使用(以 Vue3 为例)
import { onMounted, ref } from 'vue';
export default {
setup() {
const canvasRef = ref(null);
let recorder = new TouchRecorder();
onMounted(() => {
const player = new TouchPlayer(canvasRef.value);
document.getElementById('btnStart').onclick = () => recorder.start();
document.getElementById('btnStop').onclick = () => {
const data = recorder.stop();
player.play(data); // 立即本地回放
// 上传:axios.post('/api/touch', data);
};
});
return { canvasRef };
}
};
- 性能与合规兜底
- 节流:在
_h里加if (this._last && now - this._last < 16) return;可再降 30% 数据量 - 隐私:遇到
input[type=password]节点,直接return不记录 - 微信:若页面存在
viewport缩放,需把pageX/Y除以visualViewport.scale做反向补偿
用上面 100 行代码,你就向面试官展示了“事件模型 + 采样策略 + 回放引擎 + 工程封装 + 合规细节”的完整闭环,足以拿到移动端方向的高分。
拓展思考
- 如果轨迹需要跨设备同步,你会如何把
pageX/Y转成相对节点百分比?提示:用getBoundingClientRect计算参考框,再乘以 10000 取整,可压缩到 2 字节。 - 当页面出现横竖屏旋转,采集阶段记录了
orientation角度,回放时如何自动旋转画布让轨迹不漂移? - 要在小程序 web-view 里回放,但 web-view 层级最低,你会用
cover-image还是离屏 canvas 逐帧导出 base64 来避开遮挡? - 如果产品要求“热区点击检测”,你会在回放阶段用颜色采样还是路径碰撞来判断用户是否点中按钮?两者在 4K 屏下的性能差距有多大?
把以上四点任选一个展开,就能让面试官看到你不止于 MVP,而是具备大型业务落地的潜力。