js实现手绘
使用Canvas API实现手绘功能
在JavaScript中实现手绘功能通常通过HTML5的Canvas API完成。以下是基本实现方法:
const canvas = document.getElementById('drawingCanvas');
const ctx = canvas.getContext('2d');
let isDrawing = false;
canvas.addEventListener('mousedown', startDrawing);
canvas.addEventListener('mousemove', draw);
canvas.addEventListener('mouseup', stopDrawing);
canvas.addEventListener('mouseout', stopDrawing);
function startDrawing(e) {
isDrawing = true;
draw(e);
}
function draw(e) {
if (!isDrawing) return;
ctx.lineWidth = 5;
ctx.lineCap = 'round';
ctx.strokeStyle = '#000000';
ctx.lineTo(e.clientX - canvas.offsetLeft, e.clientY - canvas.offsetTop);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(e.clientX - canvas.offsetLeft, e.clientY - canvas.offsetTop);
}
function stopDrawing() {
isDrawing = false;
ctx.beginPath();
}
添加触摸屏支持
为移动设备添加触摸支持需要额外事件监听:
canvas.addEventListener('touchstart', handleTouchStart);
canvas.addEventListener('touchmove', handleTouchMove);
canvas.addEventListener('touchend', handleTouchEnd);
function handleTouchStart(e) {
e.preventDefault();
const touch = e.touches[0];
startDrawing(touch);
}
function handleTouchMove(e) {
e.preventDefault();
const touch = e.touches[0];
draw(touch);
}
function handleTouchEnd() {
stopDrawing();
}
实现笔刷样式自定义
扩展绘图功能以支持不同笔刷样式:
let currentColor = '#000000';
let currentWidth = 5;
function setColor(color) {
currentColor = color;
}
function setWidth(width) {
currentWidth = width;
}
function draw(e) {
if (!isDrawing) return;
ctx.lineWidth = currentWidth;
ctx.lineCap = 'round';
ctx.strokeStyle = currentColor;
ctx.lineTo(e.clientX - canvas.offsetLeft, e.clientY - canvas.offsetTop);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(e.clientX - canvas.offsetLeft, e.clientY - canvas.offsetTop);
}
实现撤销功能
使用数组保存绘图状态以实现撤销:
const drawingHistory = [];
let historyIndex = -1;
function saveDrawingState() {
historyIndex++;
if (historyIndex < drawingHistory.length) {
drawingHistory.length = historyIndex;
}
drawingHistory.push(canvas.toDataURL());
}
function undo() {
if (historyIndex <= 0) return;
historyIndex--;
const img = new Image();
img.onload = function() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0);
};
img.src = drawingHistory[historyIndex];
}
// 在每次绘制结束时调用saveDrawingState()
优化绘制性能
使用requestAnimationFrame优化绘制性能:
let lastX = 0;
let lastY = 0;
function draw(e) {
if (!isDrawing) return;
ctx.lineWidth = currentWidth;
ctx.lineCap = 'round';
ctx.strokeStyle = currentColor;
requestAnimationFrame(() => {
ctx.beginPath();
ctx.moveTo(lastX, lastY);
ctx.lineTo(e.clientX - canvas.offsetLeft, e.clientY - canvas.offsetTop);
ctx.stroke();
});
lastX = e.clientX - canvas.offsetLeft;
lastY = e.clientY - canvas.offsetTop;
}
function startDrawing(e) {
isDrawing = true;
lastX = e.clientX - canvas.offsetLeft;
lastY = e.clientY - canvas.offsetTop;
}
保存绘图结果
实现将绘图保存为图像文件:

function saveDrawing() {
const link = document.createElement('a');
link.download = 'drawing.png';
link.href = canvas.toDataURL('image/png');
link.click();
}






