js实现画画
使用 Canvas API 绘制图形
HTML5 的 Canvas API 是 JavaScript 实现绘图功能的核心工具。通过获取画布上下文,可以绘制线条、形状、文本等。
<canvas id="myCanvas" width="500" height="500"></canvas>
<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// 绘制矩形
ctx.fillStyle = 'red';
ctx.fillRect(10, 10, 100, 100);
// 绘制圆形
ctx.beginPath();
ctx.arc(200, 200, 50, 0, Math.PI * 2);
ctx.fillStyle = 'blue';
ctx.fill();
</script>
实现自由绘制功能
通过监听鼠标事件,可以创建简单的绘图板功能。记录鼠标移动轨迹并连接成线。
let isDrawing = false;
canvas.addEventListener('mousedown', startDrawing);
canvas.addEventListener('mousemove', draw);
canvas.addEventListener('mouseup', stopDrawing);
canvas.addEventListener('mouseout', stopDrawing);
function startDrawing(e) {
isDrawing = true;
ctx.beginPath();
ctx.moveTo(e.offsetX, e.offsetY);
}
function draw(e) {
if (!isDrawing) return;
ctx.lineTo(e.offsetX, e.offsetY);
ctx.strokeStyle = 'black';
ctx.lineWidth = 5;
ctx.stroke();
}
function stopDrawing() {
isDrawing = false;
}
添加绘图工具和颜色选择
扩展功能包括笔刷大小调整、颜色选择和工具切换。
<input type="color" id="colorPicker">
<input type="range" id="brushSize" min="1" max="50" value="5">
<button id="clearBtn">清除画布</button>
<script>
const colorPicker = document.getElementById('colorPicker');
const brushSize = document.getElementById('brushSize');
const clearBtn = document.getElementById('clearBtn');
clearBtn.addEventListener('click', () => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
});
function draw(e) {
if (!isDrawing) return;
ctx.lineTo(e.offsetX, e.offsetY);
ctx.strokeStyle = colorPicker.value;
ctx.lineWidth = brushSize.value;
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
ctx.stroke();
}
</script>
实现图像保存功能
可以将画布内容导出为图片文件,支持 PNG 或 JPEG 格式。
document.getElementById('saveBtn').addEventListener('click', () => {
const link = document.createElement('a');
link.download = 'drawing.png';
link.href = canvas.toDataURL('image/png');
link.click();
});
使用第三方库增强功能
对于更高级的绘图需求,可以考虑使用专业绘图库:
- Fabric.js:提供对象模型和交互功能
- Paper.js:矢量图形处理库
- Konva.js:高性能 2D 绘图库
// 使用Fabric.js示例
const fabricCanvas = new fabric.Canvas('canvas');
const rect = new fabric.Rect({
left: 100,
top: 100,
width: 50,
height: 50,
fill: 'red'
});
fabricCanvas.add(rect);
触摸屏设备支持
为移动设备添加触摸事件支持,使绘图应用能在手机和平板上使用。

canvas.addEventListener('touchstart', handleTouchStart);
canvas.addEventListener('touchmove', handleTouchMove);
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);
}






