js实现写字
使用 Canvas 实现写字效果
通过 HTML5 的 Canvas API 可以动态绘制文字,结合动画效果模拟手写过程。
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const text = "Hello World";
let index = 0;
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.font = "30px Arial";
ctx.fillText(text.substring(0, index), 10, 50);
if(index < text.length) {
index++;
setTimeout(draw, 100);
}
}
draw();
使用 SVG 动画写字
SVG 的路径动画可以更精确地模拟手写笔画效果。
<svg width="400" height="100">
<path id="path" d="" fill="none" stroke="black" stroke-width="2"/>
</svg>
<script>
const text = "Hello";
const path = document.getElementById('path');
const length = text.length * 20; // 估算路径长度
path.setAttribute('stroke-dasharray', length);
path.setAttribute('stroke-dashoffset', length);
const animate = () => {
path.style.strokeDashoffset = '0';
path.style.transition = 'stroke-dashoffset 2s ease-in-out';
};
setTimeout(animate, 500);
</script>
使用 CSS 动画模拟打字
纯 CSS 方案通过控制文字显示范围和动画时间实现打字效果。
<style>
.typewriter {
overflow: hidden;
border-right: 3px solid #000;
white-space: nowrap;
animation: typing 3s steps(30, end), blink-caret 0.5s step-end infinite;
}
@keyframes typing {
from { width: 0 }
to { width: 100% }
}
@keyframes blink-caret {
from, to { border-color: transparent }
50% { border-color: #000 }
}
</style>
<div class="typewriter">This text will appear typed.</div>
使用第三方库实现
现成的 JavaScript 库如 TypeIt 或 Typed.js 提供更丰富的写字动画功能。
// 使用 Typed.js
new Typed('#element', {
strings: ["First sentence.", "Second sentence."],
typeSpeed: 30,
backSpeed: 20,
loop: true
});
逐笔划绘制汉字
对于复杂汉字,可以分解为 SVG 路径逐笔绘制。
// 示例:使用 hanzi-writer 库
HanziWriter.create('target', '汉', {
width: 300,
height: 300,
showOutline: true,
strokeAnimationSpeed: 2
}).animate();






