一周前所长
找到我,问我有没有办法记录鼠标轨迹~~
详细的问过他的具体需求之后,发现是要做成这样的,以下为效果图:
思考
- 如何记录鼠标轨迹
记录鼠标轨迹的方法很简单,记录鼠标每次move
事件的前后两个点坐标即可。 - 如何重绘
我们通过记录鼠标在canvas中的点的相对坐标可以得到一个对象数组,通过requestAnimationFrame
递归对数组进行循环操作,相关代码如下:
redraw (context) {
if (localStorage.getItem('history')) {
let history = JSON.parse(localStorage.getItem('history'))
const len = history.length
let i = 0
const runner = () => {
if (i < len) {
this.draw(context, history[i][0], history[i++][1]) //绘制两点之间的连线
requestAnimationFrame(runner) //递归调用
}
}
requestAnimationFrame(runner)
}
}
组件源码
<template>
<section>
<button @click="reload">开始重绘</button>
<button @click="reset">重置右侧画板</button>
<h1>测试画板</h1>
<canvas id="panel1" width