这是another thread的延续。
我已经在带有时间戳的mousemove事件上记录了鼠标坐标,我现在想要重放这个坐标集合并根据它移动模拟光标(img)。
我尝试过从前一个线程实现解决方案,但我不知道如何实际执行此操作。
这是需要发生的事情:
我已经尝试过使用setInterval和一个超时函数,但它不能正常工作,尝试代码,也许你可以想出一个解决方案。
只有您需要运行它才能充当光标的图像。
import React from 'react'
import cursor from '../../assets/images/cursor.png'
export default class Tracker extends React.Component {
constructor() {
super()
this.state = {
tracking: [],
replay: false,
replayPoint: null,
}
}
onMouseMove = event => {
let newArr = this.state.tracking.slice()
newArr.push({ time: Date.now(), x: event.clientX, y: event.clientY })
this.setState({ tracking: newArr })
}
stopTracking = () => {
window.removeEventListener('mousemove', this.onMouseMove)
this.setState({ replay: true, replayPoint: { x: 0, y: 0 } })
this.state.tracking.forEach(function(p, i, array) {
let that = this
if (i + 1 < array.length) {
let interval = array[i + 1].time - p.time
setTimeout(function() {
that.moveCursor(p)
that.sleep(interval)
}, interval)
}
}, this)
}
moveCursor = p => {
this.setState({
replayPoint: { x: p.x, y: p.y },
})
}
sleep(milliseconds) {
var start = new Date().getTime()
for (var i = 0; i < 1e7; i++) {
if (new Date().getTime() - start > milliseconds) {
break
}
}
}
render() {
let cursor = this.state.replay && <Cursor cords={this.state.replayPoint} />
return (
<div>
{cursor}
<button onClick={this.stopTracking}>Stop tracking</button>
</div>
)
}
componentDidMount() {
window.addEventListener('mousemove', this.onMouseMove)
}
}
class Cursor extends React.PureComponent {
render() {
const { x, y } = this.props.cords
console.log('move to ' + x + ' - ' + y)
return (
<div>
<img
src={cursor}
style={{
left: x + 'px',
top: y + 'px',
position: 'fixed',
width: '20px',
}}
/>
</div>
)
}
}