js实现画笔
实现基础画布
创建一个HTML文件,包含一个<canvas>元素作为画布。设置画布的宽度和高度以适应需求。
<canvas id="drawingCanvas" width="800" height="600"></canvas>
初始化画布上下文
使用JavaScript获取画布元素并初始化2D渲染上下文。设置画笔的默认样式,如颜色、线条宽度等。
const canvas = document.getElementById('drawingCanvas');
const ctx = canvas.getContext('2d');
ctx.strokeStyle = '#000000';
ctx.lineWidth = 5;
ctx.lineCap = 'round';
监听鼠标事件
为画布添加鼠标事件监听器,包括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;
drawLine(lastX, lastY, e.offsetX, e.offsetY);
[lastX, lastY] = [e.offsetX, e.offsetY];
});
canvas.addEventListener('mouseup', () => isDrawing = false);
canvas.addEventListener('mouseout', () => isDrawing = false);
实现绘图函数
定义drawLine函数,使用beginPath、moveTo、lineTo和stroke方法绘制线条。
function drawLine(x1, y1, x2, y2) {
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();
}
添加触摸支持
为移动设备添加触摸事件支持,处理触摸位置并适配绘图逻辑。

canvas.addEventListener('touchstart', (e) => {
e.preventDefault();
isDrawing = true;
const rect = canvas.getBoundingClientRect();
[lastX, lastY] = [e.touches[0].clientX - rect.left, e.touches[0].clientY - rect.top];
});
canvas.addEventListener('touchmove', (e) => {
e.preventDefault();
if (!isDrawing) return;
const rect = canvas.getBoundingClientRect();
const x = e.touches[0].clientX - rect.left;
const y = e.touches[0].clientY - rect.top;
drawLine(lastX, lastY, x, y);
[lastX, lastY] = [x, y];
});
canvas.addEventListener('touchend', () => isDrawing = false);
添加颜色和粗细选择
扩展功能,允许用户选择画笔颜色和线条粗细。可以通过HTML输入元素实现。
<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', (e) => ctx.strokeStyle = e.target.value);
brushSize.addEventListener('input', (e) => ctx.lineWidth = e.target.value);
实现清除画布功能
添加一个按钮,用于清除画布内容。调用clearRect方法重置画布。
<button id="clearCanvas">Clear</button>
document.getElementById('clearCanvas').addEventListener('click', () => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
});
保存绘图结果
添加保存功能,将画布内容导出为图像。使用toDataURL方法生成图像数据。
<button id="saveCanvas">Save</button>
document.getElementById('saveCanvas').addEventListener('click', () => {
const link = document.createElement('a');
link.download = 'drawing.png';
link.href = canvas.toDataURL('image/png');
link.click();
});






