js 实现画板
使用 Canvas API 实现基础画板
HTML 中创建 <canvas> 元素并设置宽高:
<canvas id="drawing-board" width="800" height="600"></canvas>
JavaScript 获取画布上下文并初始化绘图参数:
const canvas = document.getElementById('drawing-board');
const ctx = canvas.getContext('2d');
let isDrawing = false;
let currentColor = '#000000';
let brushSize = 5;
鼠标事件绑定实现绘图功能
监听鼠标事件控制绘图状态:
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.lineCap = 'round';
ctx.lineJoin = 'round';
ctx.strokeStyle = currentColor;
ctx.lineWidth = brushSize;
ctx.lineTo(e.offsetX, e.offsetY);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(e.offsetX, e.offsetY);
}
function stopDrawing() {
isDrawing = false;
ctx.beginPath();
}
添加颜色和粗细控制功能
创建颜色选择器和画笔粗细滑块:
<input type="color" id="color-picker" value="#000000">
<input type="range" id="brush-size" min="1" max="50" value="5">
JavaScript 更新绘图参数:
document.getElementById('color-picker').addEventListener('change', (e) => {
currentColor = e.target.value;
});
document.getElementById('brush-size').addEventListener('input', (e) => {
brushSize = e.target.value;
});
实现清除画布功能
添加清除按钮和对应逻辑:
<button id="clear-btn">清除画布</button>
<script>
document.getElementById('clear-btn').addEventListener('click', () => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
});
</script>
保存绘图为图片
添加保存功能按钮:
<button id="save-btn">保存图片</button>
<script>
document.getElementById('save-btn').addEventListener('click', () => {
const link = document.createElement('a');
link.download = 'drawing.png';
link.href = canvas.toDataURL('image/png');
link.click();
});
</script>
响应式布局优化
CSS 确保画布适应不同屏幕:
canvas {
border: 1px solid #000;
display: block;
margin: 0 auto;
background-color: white;
}
.controls {
display: flex;
justify-content: center;
gap: 20px;
margin: 10px;
}
触摸屏设备支持
添加触摸事件处理:
canvas.addEventListener('touchstart', handleTouchStart);
canvas.addEventListener('touchmove', handleTouchMove);
canvas.addEventListener('touchend', handleTouchEnd);
function handleTouchStart(e) {
e.preventDefault();
const touch = e.touches[0];
const mouseEvent = new MouseEvent('mousedown', {
clientX: touch.clientX,
clientY: touch.clientY
});
canvas.dispatchEvent(mouseEvent);
}
function handleTouchMove(e) {
e.preventDefault();
const touch = e.touches[0];
const mouseEvent = new MouseEvent('mousemove', {
clientX: touch.clientX,
clientY: touch.clientY
});
canvas.dispatchEvent(mouseEvent);
}
function handleTouchEnd(e) {
e.preventDefault();
const mouseEvent = new MouseEvent('mouseup', {});
canvas.dispatchEvent(mouseEvent);
}






