vue实现文字手写
Vue 实现文字手写效果
要实现文字手写效果,可以通过 CSS 动画或 Canvas 绘制来实现。以下是两种常见的方法:
使用 CSS 动画实现逐字显示
通过 CSS @keyframes 和 animation 属性,可以模拟逐字手写效果。
<template>
<div class="handwritten-text">{{ animatedText }}</div>
</template>
<script>
export default {
data() {
return {
text: "Hello, Vue!",
animatedText: "",
};
},
mounted() {
this.animateText();
},
methods: {
animateText() {
let i = 0;
const timer = setInterval(() => {
this.animatedText += this.text[i];
i++;
if (i >= this.text.length) clearInterval(timer);
}, 100); // 控制速度,单位毫秒
},
},
};
</script>
<style>
.handwritten-text {
font-family: "Dancing Script", cursive; /* 手写风格字体 */
font-size: 24px;
white-space: pre; /* 保留空格 */
}
</style>
使用 Canvas 绘制手写动画
通过 Canvas 逐帧绘制路径,模拟手写效果。
<template>
<canvas ref="canvas" width="400" height="100"></canvas>
</template>
<script>
export default {
mounted() {
this.drawHandwriting();
},
methods: {
drawHandwriting() {
const canvas = this.$refs.canvas;
const ctx = canvas.getContext("2d");
const text = "Vue Handwriting";
const points = this.generatePathPoints(text, 20, 50);
let i = 0;
const drawInterval = setInterval(() => {
if (i >= points.length) {
clearInterval(drawInterval);
return;
}
ctx.lineTo(points[i].x, points[i].y);
ctx.stroke();
i++;
}, 50); // 控制绘制速度
},
generatePathPoints(text, x, y) {
const points = [];
const ctx = document.createElement("canvas").getContext("2d");
ctx.font = "24px 'Dancing Script', cursive";
const path = new Path2D();
path.addText(text, { x, y }, ctx.font);
// 模拟路径点(简化版)
for (let i = 0; i < text.length * 10; i++) {
points.push({ x: x + i * 2, y: y + Math.sin(i * 0.2) * 5 });
}
return points;
},
},
};
</script>
使用第三方库(如 Rough.js)
Rough.js 可以生成手写风格的图形和文字。
<template>
<div ref="roughContainer"></div>
</template>
<script>
import rough from "roughjs";
export default {
mounted() {
this.drawRoughText();
},
methods: {
drawRoughText() {
const rc = rough.svg(this.$refs.roughContainer);
const node = rc.text(20, 50, "Vue Rough Text", {
font: "24px 'Dancing Script', cursive",
roughness: 1,
});
this.$refs.roughContainer.appendChild(node);
},
},
};
</script>
注意事项
- 字体选择:使用手写风格字体(如
Dancing Script、Pacifico)增强效果。 - 性能优化:对于长文本,避免频繁的 DOM 操作,优先使用 Canvas。
- 响应式适配:在移动端调整字体大小和动画速度。
通过以上方法,可以在 Vue 中实现自然的文字手写效果。







