js 实现画笔
使用 Canvas API 实现基础画笔功能
通过 HTML5 的 <canvas> 元素和 JavaScript 的 Canvas API 可以轻松实现画笔功能。以下是一个基础实现示例:
<canvas id="drawingCanvas" width="800" height="600"></canvas>
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;
ctx.beginPath();
ctx.moveTo(e.offsetX, e.offsetY);
}
function draw(e) {
if (!isDrawing) return;
ctx.lineTo(e.offsetX, e.offsetY);
ctx.stroke();
}
function stopDrawing() {
isDrawing = false;
}
添加画笔样式控制
可以通过修改上下文属性来自定义画笔样式:
// 设置画笔颜色和宽度
ctx.strokeStyle = '#000000'; // 黑色
ctx.lineWidth = 5;
ctx.lineCap = 'round'; // 圆形线帽
ctx.lineJoin = 'round'; // 圆形连接
实现触摸屏支持
为支持移动设备,需要添加触摸事件处理:

canvas.addEventListener('touchstart', handleTouchStart);
canvas.addEventListener('touchmove', handleTouchMove);
canvas.addEventListener('touchend', handleTouchEnd);
function handleTouchStart(e) {
e.preventDefault();
const touch = e.touches[0];
const mouseEvent = new MouseEvent('mousedown', {
clientX: touch.clientX,
clientY: touch.clientY
});
canvas.dispatchEvent(mouseEvent);
}
function handleTouchMove(e) {
e.preventDefault();
const touch = e.touches[0];
const mouseEvent = new MouseEvent('mousemove', {
clientX: touch.clientX,
clientY: touch.clientY
});
canvas.dispatchEvent(mouseEvent);
}
function handleTouchEnd(e) {
e.preventDefault();
const mouseEvent = new MouseEvent('mouseup', {});
canvas.dispatchEvent(mouseEvent);
}
实现橡皮擦功能
通过设置全局复合操作可以实现橡皮擦:
function activateEraser() {
ctx.globalCompositeOperation = 'destination-out';
ctx.lineWidth = 20; // 橡皮擦大小
}
function activateBrush() {
ctx.globalCompositeOperation = 'source-over';
ctx.lineWidth = 5; // 恢复画笔大小
}
保存画布内容
可以将画布内容保存为图像:

function saveCanvas() {
const image = canvas.toDataURL('image/png');
const link = document.createElement('a');
link.download = 'drawing.png';
link.href = image;
link.click();
}
清除画布
重置整个画布:
function clearCanvas() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
使用第三方库简化开发
对于更复杂的需求,可以考虑使用专门的绘图库:
- Paper.js - 适合矢量图形绘制
- Fabric.js - 提供丰富的图形对象和交互功能
- Konva.js - 高性能的2D绘图库
这些库提供了更高级的功能和更好的性能优化,适合复杂绘图应用的开发。






