js实现画笔功能
实现基础画布与画笔功能
创建一个HTML文件并添加<canvas>元素作为画布。通过JavaScript获取画布上下文并设置初始样式:
<canvas id="drawCanvas" width="800" height="600"></canvas>
<script>
const canvas = document.getElementById('drawCanvas');
const ctx = canvas.getContext('2d');
ctx.strokeStyle = '#000000';
ctx.lineWidth = 5;
ctx.lineCap = 'round';
</script>
监听鼠标事件实现绘制
绑定鼠标事件来跟踪绘制动作。需要处理mousedown、mousemove和mouseup事件:
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);
添加触摸屏支持
为移动设备添加触摸事件处理:

canvas.addEventListener('touchstart', (e) => {
e.preventDefault();
isDrawing = true;
const touch = e.touches[0];
const rect = canvas.getBoundingClientRect();
[lastX, lastY] = [touch.clientX - rect.left, touch.clientY - rect.top];
});
canvas.addEventListener('touchmove', (e) => {
if (!isDrawing) return;
e.preventDefault();
const touch = e.touches[0];
const rect = canvas.getBoundingClientRect();
const x = touch.clientX - rect.left;
const y = touch.clientY - rect.top;
ctx.beginPath();
ctx.moveTo(lastX, lastY);
ctx.lineTo(x, y);
ctx.stroke();
[lastX, lastY] = [x, y];
});
canvas.addEventListener('touchend', () => isDrawing = false);
实现画笔属性调整
添加控制面板来调整画笔颜色和粗细:
<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;
});
添加清除画布功能
实现清除按钮来重置画布:

<button id="clearBtn">清除画布</button>
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);
});
保存绘制内容
添加保存功能将画布内容导出为图片:
<button id="saveBtn">保存图片</button>
document.getElementById('saveBtn').addEventListener('click', () => {
const link = document.createElement('a');
link.download = 'drawing.png';
link.href = canvas.toDataURL('image/png');
link.click();
});






