js实现画笔
使用Canvas实现基础画笔功能
在HTML中创建Canvas元素并设置基本样式
<canvas id="drawingCanvas" width="800" height="600"></canvas>
获取Canvas上下文并初始化画笔参数
const canvas = document.getElementById('drawingCanvas');
const ctx = canvas.getContext('2d');
let isDrawing = false;
let brushSize = 5;
let brushColor = '#000000';
实现鼠标事件监听绘制路径
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 = brushSize;
ctx.lineCap = 'round';
ctx.strokeStyle = brushColor;
ctx.lineTo(e.offsetX, e.offsetY);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(e.offsetX, e.offsetY);
}
function stopDrawing() {
isDrawing = false;
ctx.beginPath();
}
添加画笔属性控制功能
实现画笔大小和颜色控制
document.getElementById('brushSize').addEventListener('change', function(e) {
brushSize = e.target.value;
});
document.getElementById('colorPicker').addEventListener('input', function(e) {
brushColor = e.target.value;
});
清除画布功能
document.getElementById('clearCanvas').addEventListener('click', function() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
});
实现触摸屏支持
添加触摸事件处理
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);
}
}
保存绘制内容
实现画布保存为图片
document.getElementById('saveCanvas').addEventListener('click', function() {
const dataURL = canvas.toDataURL('image/png');
const link = document.createElement('a');
link.download = 'drawing.png';
link.href = dataURL;
link.click();
});
高级画笔功能实现
虚线画笔效果
function setDashedBrush() {
ctx.setLineDash([5, 3]);
}
function setSolidBrush() {
ctx.setLineDash([]);
}
压力敏感画笔(需支持压感设备)
canvas.addEventListener('mousemove', function(e) {
if (e.pressure) {
brushSize = e.pressure * 10;
}
});
性能优化建议
使用requestAnimationFrame优化绘制
function drawOptimized(e) {
if (!isDrawing) return;
requestAnimationFrame(() => {
ctx.lineWidth = brushSize;
ctx.strokeStyle = brushColor;
ctx.lineTo(e.offsetX, e.offsetY);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(e.offsetX, e.offsetY);
});
}
实现绘制历史记录
const history = [];
let historyIndex = -1;
function saveState() {
historyIndex++;
if (historyIndex < history.length) {
history.length = historyIndex;
}
history.push(canvas.toDataURL());
}
function undo() {
if (historyIndex <= 0) return;
historyIndex--;
const img = new Image();
img.onload = function() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0);
};
img.src = history[historyIndex];
}






