js实现画笔
使用Canvas API实现基础画笔功能
在HTML中创建<canvas>元素并设置宽高
<canvas id="drawCanvas" width="800" height="600"></canvas>
获取Canvas上下文并设置画笔样式
const canvas = document.getElementById('drawCanvas');
const ctx = canvas.getContext('2d');
ctx.strokeStyle = '#000000';
ctx.lineWidth = 5;
ctx.lineCap = 'round';
实现鼠标绘制逻辑
let isDrawing = false;
let lastX = 0;
let lastY = 0;
canvas.addEventListener('mousedown', (e) => {
isDrawing = true;
[lastX, lastY] = [e.offsetX, e.offsetY];
});
canvas.addEventListener('mousemove', (e) => {
if (!isDrawing) return;
ctx.beginPath();
ctx.moveTo(lastX, lastY);
ctx.lineTo(e.offsetX, e.offsetY);
ctx.stroke();
[lastX, lastY] = [e.offsetX, e.offsetY];
});
canvas.addEventListener('mouseup', () => isDrawing = false);
canvas.addEventListener('mouseout', () => isDrawing = false);
添加触摸屏支持
扩展事件监听以支持触摸设备

function getTouchPos(canvasDom, touchEvent) {
const rect = canvasDom.getBoundingClientRect();
return {
x: touchEvent.touches[0].clientX - rect.left,
y: touchEvent.touches[0].clientY - rect.top
};
}
canvas.addEventListener('touchstart', (e) => {
e.preventDefault();
const pos = getTouchPos(canvas, e);
isDrawing = true;
[lastX, lastY] = [pos.x, pos.y];
});
canvas.addEventListener('touchmove', (e) => {
e.preventDefault();
if (!isDrawing) return;
const pos = getTouchPos(canvas, e);
ctx.beginPath();
ctx.moveTo(lastX, lastY);
ctx.lineTo(pos.x, pos.y);
ctx.stroke();
[lastX, lastY] = [pos.x, pos.y];
});
canvas.addEventListener('touchend', () => isDrawing = false);
实现画笔属性控制
添加颜色选择功能
document.getElementById('colorPicker').addEventListener('change', (e) => {
ctx.strokeStyle = e.target.value;
});
添加线宽控制

document.getElementById('brushSize').addEventListener('input', (e) => {
ctx.lineWidth = e.target.value;
});
添加清除画布功能
实现清除按钮
document.getElementById('clearBtn').addEventListener('click', () => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
});
优化绘制性能
使用requestAnimationFrame优化绘制
function draw(e) {
if (!isDrawing) return;
ctx.beginPath();
ctx.moveTo(lastX, lastY);
ctx.lineTo(e.offsetX, e.offsetY);
ctx.stroke();
[lastX, lastY] = [e.offsetX, e.offsetY];
requestAnimationFrame(() => draw(e));
}
canvas.addEventListener('mousedown', (e) => {
isDrawing = true;
[lastX, lastY] = [e.offsetX, e.offsetY];
draw(e);
});
保存绘图结果
实现保存为图片功能
document.getElementById('saveBtn').addEventListener('click', () => {
const link = document.createElement('a');
link.download = 'drawing.png';
link.href = canvas.toDataURL('image/png');
link.click();
});






