当前位置:首页 > JavaScript

js实现写字

2026-01-31 21:24:21JavaScript

使用 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 路径逐笔绘制。

js实现写字

// 示例:使用 hanzi-writer 库
HanziWriter.create('target', '汉', {
    width: 300,
    height: 300,
    showOutline: true,
    strokeAnimationSpeed: 2
}).animate();

标签: js
分享给朋友:

相关文章

js实现选题

js实现选题

实现选题功能的JavaScript方法 基础实现方案 使用数组存储选项,通过随机索引选取: const options = ['选项A', '选项B', '选项C', '选项D']; const r…

使用js实现

使用js实现

使用JavaScript实现 JavaScript可以通过Math.random()函数生成随机数,结合其他方法可以实现多种随机数生成需求。 // 生成0到1之间的随机小数 const random…

js实现求导

js实现求导

实现数值求导的方法 在JavaScript中实现求导通常采用数值方法,因为JavaScript不是符号计算语言。以下是常见的数值微分方法: 中心差分法 中心差分法提供较高精度的导数近似: func…

链表实现js

链表实现js

链表的基本概念 链表是一种线性数据结构,由一系列节点组成,每个节点包含数据和一个指向下一个节点的指针(单向链表)或两个指针(双向链表)。与数组不同,链表在内存中非连续存储,插入和删除操作更高效,但随机…

节流js实现

节流js实现

节流(Throttle)的实现原理 节流是一种限制函数执行频率的技术,确保函数在一定时间间隔内最多执行一次。适用于高频触发事件(如滚动、输入、窗口调整等)的场景。 基础实现方式 使用时间戳判断是否执…

js实现滚动

js实现滚动

实现滚动效果的方法 在JavaScript中实现滚动效果可以通过多种方式完成,以下是一些常见的方法: 使用window.scrollTo() window.scrollTo()方法可以将页面滚动到指…