h5实现手写
实现H5手写功能的方法
H5手写功能可以通过HTML5的Canvas元素结合JavaScript实现。以下是具体实现步骤:
创建Canvas画布
在HTML中创建Canvas元素并设置基本样式:
<canvas id="handwritingCanvas" width="800" height="600" style="border:1px solid #000;"></canvas>
初始化绘图上下文
通过JavaScript获取Canvas上下文并设置绘图属性:
const canvas = document.getElementById('handwritingCanvas');
const ctx = canvas.getContext('2d');
ctx.strokeStyle = '#000000';
ctx.lineWidth = 3;
ctx.lineCap = 'round';
实现绘图逻辑
绑定鼠标/触摸事件实现绘图功能:

let isDrawing = false;
// 鼠标/触摸开始
canvas.addEventListener('mousedown', startDrawing);
canvas.addEventListener('touchstart', startDrawing);
// 鼠标/触摸移动
canvas.addEventListener('mousemove', draw);
canvas.addEventListener('touchmove', draw);
// 鼠标/触摸结束
canvas.addEventListener('mouseup', stopDrawing);
canvas.addEventListener('touchend', stopDrawing);
function startDrawing(e) {
isDrawing = true;
draw(e);
}
function draw(e) {
if (!isDrawing) return;
const rect = canvas.getBoundingClientRect();
const x = (e.clientX || e.touches[0].clientX) - rect.left;
const y = (e.clientY || e.touches[0].clientY) - rect.top;
ctx.lineTo(x, y);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(x, y);
}
function stopDrawing() {
isDrawing = false;
ctx.beginPath();
}
添加清除功能
实现清除画布的功能:
document.getElementById('clearBtn').addEventListener('click', function() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
});
保存手写内容
将Canvas内容保存为图片:
document.getElementById('saveBtn').addEventListener('click', function() {
const dataURL = canvas.toDataURL('image/png');
const link = document.createElement('a');
link.download = 'handwriting.png';
link.href = dataURL;
link.click();
});
移动端适配
针对移动设备添加触摸事件支持:

// 阻止触摸事件的默认行为(防止页面滚动)
canvas.addEventListener('touchmove', function(e) {
if (isDrawing) e.preventDefault();
}, { passive: false });
优化绘图性能
使用requestAnimationFrame优化绘图流畅度:
function draw(e) {
if (!isDrawing) return;
requestAnimationFrame(() => {
const rect = canvas.getBoundingClientRect();
const x = (e.clientX || e.touches[0].clientX) - rect.left;
const y = (e.clientY || e.touches[0].clientY) - rect.top;
ctx.lineTo(x, y);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(x, y);
});
}
添加笔迹样式选项
提供多种笔迹样式选择:
document.getElementById('colorPicker').addEventListener('change', function(e) {
ctx.strokeStyle = e.target.value;
});
document.getElementById('widthSlider').addEventListener('input', function(e) {
ctx.lineWidth = e.target.value;
});
实现橡皮擦功能
添加橡皮擦功能切换:
let isEraser = false;
document.getElementById('eraserBtn').addEventListener('click', function() {
isEraser = !isEraser;
if (isEraser) {
ctx.globalCompositeOperation = 'destination-out';
} else {
ctx.globalCompositeOperation = 'source-over';
}
});
以上方法可以实现一个完整的H5手写功能,支持PC和移动设备,包含基本绘图、清除、保存等功能。可以根据实际需求进一步扩展功能。






