在vue3中怎么实现鼠标,经过的地方留下相应的直线
时间: 2024-02-13 22:07:44 浏览: 128
要实现鼠标经过留下直线的效果,可以在Vue3中使用`@mousemove`事件监听器和`<canvas>`标签来实现。具体步骤如下:
1.在Vue组件的`<template>`标签中添加一个`<canvas>`标签,并设置它的宽度和高度,如下所示:
```html
<template>
<canvas ref="canvas" width="800" height="600"></canvas>
</template>
```
2.在Vue组件的`<script>`标签中,使用`setup()`函数来注册`@mousemove`事件监听器,并在事件处理函数中获取鼠标的坐标位置,如下所示:
```js
import { onMounted, ref } from 'vue'
export default {
setup() {
const canvas = ref(null)
const mouse = ref({ x: 0, y: 0 })
// 监听鼠标移动事件
const handleMouseMove = (event) => {
const rect = canvas.value.getBoundingClientRect()
mouse.value.x = event.clientX - rect.left
mouse.value.y = event.clientY - rect.top
}
onMounted(() => {
canvas.value.addEventListener('mousemove', handleMouseMove)
})
return {
canvas,
mouse
}
}
}
```
3.在`<canvas>`标签中,使用`ctx.beginPath()`和`ctx.lineTo()`方法来绘制直线,如下所示:
```js
import { onMounted, ref } from 'vue'
export default {
setup() {
const canvas = ref(null)
const mouse = ref({ x: 0, y: 0 })
// 监听鼠标移动事件
const handleMouseMove = (event) => {
const rect = canvas.value.getBoundingClientRect()
mouse.value.x = event.clientX - rect.left
mouse.value.y = event.clientY - rect.top
}
onMounted(() => {
canvas.value.addEventListener('mousemove', handleMouseMove)
const ctx = canvas.value.getContext('2d')
// 绘制直线
ctx.beginPath()
ctx.moveTo(0, 0)
ctx.lineTo(mouse.value.x, mouse.value.y)
ctx.stroke()
})
return {
canvas,
mouse
}
}
}
```
4.为了让直线能够随着鼠标移动而变化,需要在`handleMouseMove()`函数中重新绘制直线,如下所示:
```js
import { onMounted, ref } from 'vue'
export default {
setup() {
const canvas = ref(null)
const mouse = ref({ x: 0, y: 0 })
// 监听鼠标移动事件
const handleMouseMove = (event) => {
const rect = canvas.value.getBoundingClientRect()
mouse.value.x = event.clientX - rect.left
mouse.value.y = event.clientY - rect.top
const ctx = canvas.value.getContext('2d')
// 清除画布
ctx.clearRect(0, 0, canvas.value.width, canvas.value.height)
// 绘制直线
ctx.beginPath()
ctx.moveTo(0, 0)
ctx.lineTo(mouse.value.x, mouse.value.y)
ctx.stroke()
}
onMounted(() => {
canvas.value.addEventListener('mousemove', handleMouseMove)
})
return {
canvas,
mouse
}
}
}
```
这样,当鼠标在`<canvas>`标签上移动时,就会留下相应的直线。
阅读全文