js实现手绘
使用Canvas实现手绘功能
在JavaScript中,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();
}
实现画笔属性调整
添加画笔颜色和大小调整功能:
function changeColor(color) {
ctx.strokeStyle = color;
}
function changeSize(size) {
ctx.lineWidth = size;
}
添加清除画布功能
function clearCanvas() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
保存绘图为图像
function saveDrawing() {
const image = canvas.toDataURL('image/png');
const link = document.createElement('a');
link.download = 'drawing.png';
link.href = image;
link.click();
}
实现平滑绘制
使用二次贝塞尔曲线使线条更平滑:
let lastX = 0;
let lastY = 0;
function drawSmooth(e) {
if (!isDrawing) return;
ctx.lineWidth = 5;
ctx.lineCap = 'round';
ctx.strokeStyle = '#000000';
const currentX = e.clientX - canvas.offsetLeft;
const currentY = e.clientY - canvas.offsetTop;
ctx.beginPath();
ctx.moveTo(lastX, lastY);
ctx.quadraticCurveTo(
lastX, lastY,
(currentX + lastX) / 2, (currentY + lastY) / 2
);
ctx.stroke();
lastX = currentX;
lastY = currentY;
}
添加撤销功能
使用数组保存绘图状态:

const drawingHistory = [];
let historyIndex = -1;
function saveState() {
historyIndex++;
if (historyIndex < drawingHistory.length) {
drawingHistory.length = historyIndex;
}
drawingHistory.push(canvas.toDataURL());
}
function undo() {
if (historyIndex <= 0) {
clearCanvas();
historyIndex = -1;
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];
}
这些代码片段组合起来可以创建一个功能完整的手绘应用,包括基本绘制、触摸支持、属性调整和撤销功能。根据具体需求可以进一步扩展功能,如添加不同画笔样式、图层支持或更高级的绘图工具。






