Canvas 一笔一画写汉字:简单实现指南
以下是一个简单的实现:
- 首先,需要一个 HTML 页面,包含一个 canvas 元素和一个文本输入框用于输入汉字。
 
<!DOCTYPE html>
<html>
<head>
	<title>canvas写字</title>
	<meta charset="utf-8">
	<style>
		canvas{
			border: 1px solid #ccc;
		}
	</style>
</head>
<body>
	<input type="text" id="text" placeholder="请输入汉字">
	<canvas id="canvas" width="400" height="400"></canvas>
	<script src="script.js"></script>
</body>
</html>
- 在 JavaScript 文件中获取 canvas 元素和文本输入框,同时注册文本输入框的 keyup 事件。
 
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const input = document.getElementById('text');
input.addEventListener('keyup', function(e){
    // 获取输入的汉字
    let text = input.value.trim();
    // 调用绘制函数
    drawText(text);
})
- 编写绘制函数 drawText,该函数负责将汉字一笔一画地绘制在 canvas 上。
 
function drawText(text){
    // 清空 canvas
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    // 设置绘制字体
    ctx.font = '50px 宋体';
    // 获取汉字的路径
    let path = ctx.measureText(text).width;
    // 计算汉字的起始 x 坐标
    let x = (canvas.width - path) / 2;
    // 计算汉字的起始 y 坐标
    let y = canvas.height / 2;
    // 开始绘制
    ctx.beginPath();
    // 遍历汉字的每一笔
    for(let i=0; i<text.length; i++){
        let charPath = ctx.measureText(text[i]).width;
        // 计算当前笔的起始 x 坐标
        let charX = x + (path - charPath) / 2;
        // 绘制当前笔
        ctx.fillText(text[i], charX, y);
        // 更新 x 坐标
        x += charPath;
    }
    ctx.closePath();
}
- 最后,使用 CSS 样式将 canvas 元素设置为居中显示。
 
canvas{
    margin: 0 auto;
    display: block;
}
这样就可以实现一个简单的 canvas 写汉字的效果了。
原文地址: https://www.cveoy.top/t/topic/ns8s 著作权归作者所有。请勿转载和采集!