js 实现画笔
使用 Canvas 实现画笔功能
在 HTML 中创建一个 <canvas> 元素,通过 JavaScript 监听鼠标事件来实现画笔功能。以下是核心代码示例:
<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;
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();
}
实现画笔属性控制
添加控制画笔颜色和粗细的功能:
<input type="color" id="colorPicker" value="#000000">
<input type="range" id="brushSize" min="1" max="50" value="5">
const colorPicker = document.getElementById('colorPicker');
const brushSize = document.getElementById('brushSize');
colorPicker.addEventListener('input', () => {
ctx.strokeStyle = colorPicker.value;
});
brushSize.addEventListener('input', () => {
ctx.lineWidth = brushSize.value;
});
实现橡皮擦功能
通过设置合成模式实现橡皮擦:

function activateEraser() {
ctx.globalCompositeOperation = 'destination-out';
ctx.lineWidth = 20; // 橡皮擦大小
}
function deactivateEraser() {
ctx.globalCompositeOperation = 'source-over';
}
保存画布内容
将画布内容保存为图像:
function saveCanvas() {
const link = document.createElement('a');
link.download = 'drawing.png';
link.href = canvas.toDataURL('image/png');
link.click();
}
清除画布
实现清空画布功能:
function clearCanvas() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath(); // 重置路径
}
注意事项
- 坐标计算需要考虑画布在页面中的偏移量
- 对于高DPI设备,可能需要设置画布的逻辑尺寸和显示尺寸
- 性能优化:对于复杂绘图,可以考虑使用 requestAnimationFrame
- 路径绘制需要正确管理 beginPath 和 closePath 的调用
这个实现提供了基础的画笔功能,可以根据需要进一步扩展,如添加撤销/重做、不同画笔样式、图层支持等功能。






