js 实现画笔
使用 Canvas API 实现基础画笔
HTML 中创建 <canvas> 元素并设置宽高:
<canvas id="drawCanvas" width="800" height="600"></canvas>
JavaScript 初始化画布并监听鼠标事件:
const canvas = document.getElementById('drawCanvas');
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.offsetX, e.offsetY);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(e.offsetX, e.offsetY);
}
function stopDrawing() {
isDrawing = false;
ctx.beginPath(); // 重置路径
}
添加触摸屏支持
为移动设备添加触摸事件处理:
canvas.addEventListener('touchstart', handleTouch);
canvas.addEventListener('touchmove', handleTouch);
function handleTouch(e) {
e.preventDefault();
const touch = e.touches[0];
const mouseEvent = {
offsetX: touch.clientX - canvas.offsetLeft,
offsetY: touch.clientY - canvas.offsetTop
};
if (e.type === 'touchstart') {
startDrawing(mouseEvent);
} else {
draw(mouseEvent);
}
}
实现画笔属性控制
添加颜色和粗细控制:

<input type="color" id="colorPicker" value="#000000">
<input type="range" id="brushSize" min="1" max="50" value="5">
更新绘制逻辑:
function draw(e) {
if (!isDrawing) return;
ctx.lineWidth = document.getElementById('brushSize').value;
ctx.strokeStyle = document.getElementById('colorPicker').value;
ctx.lineTo(e.offsetX, e.offsetY);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(e.offsetX, e.offsetY);
}
实现橡皮擦功能
添加橡皮擦切换按钮:

<button id="eraserBtn">橡皮擦</button>
JavaScript 切换逻辑:
let isEraser = false;
document.getElementById('eraserBtn').addEventListener('click', function() {
isEraser = !isEraser;
this.textContent = isEraser ? '画笔' : '橡皮擦';
});
function draw(e) {
if (!isDrawing) return;
ctx.lineWidth = isEraser ? 20 : document.getElementById('brushSize').value;
ctx.strokeStyle = isEraser ? '#ffffff' : document.getElementById('colorPicker').value;
ctx.lineTo(e.offsetX, e.offsetY);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(e.offsetX, e.offsetY);
}
保存画布内容
添加保存功能按钮:
<button id="saveBtn">保存图片</button>
实现保存逻辑:
document.getElementById('saveBtn').addEventListener('click', function() {
const link = document.createElement('a');
link.download = 'drawing.png';
link.href = canvas.toDataURL('image/png');
link.click();
});






