js实现画图工具
实现基础画布
使用HTML5的Canvas元素作为画布基础,通过JavaScript获取画布上下文。示例代码初始化一个全屏画布:
<canvas id="drawingCanvas" width="800" height="600"></canvas>
<script>
const canvas = document.getElementById('drawingCanvas');
const ctx = canvas.getContext('2d');
ctx.strokeStyle = '#000000';
ctx.lineWidth = 3;
</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);
绘制工具切换
通过按钮切换画笔、橡皮擦等工具。示例实现画笔和橡皮擦功能:

function setTool(toolType) {
if (toolType === 'eraser') {
ctx.globalCompositeOperation = 'destination-out';
} else {
ctx.globalCompositeOperation = 'source-over';
ctx.strokeStyle = document.getElementById('colorPicker').value;
}
}
颜色与粗细选择
添加颜色选择器和线宽滑块控制:
<input type="color" id="colorPicker" value="#000000">
<input type="range" id="brushSize" min="1" max="50" value="3">
<script>
document.getElementById('colorPicker').addEventListener('change', (e) => {
ctx.strokeStyle = e.target.value;
});
document.getElementById('brushSize').addEventListener('change', (e) => {
ctx.lineWidth = e.target.value;
});
</script>
图形绘制功能
扩展功能支持绘制矩形、圆形等预设图形:

function drawShape(shape, startX, startY, endX, endY) {
ctx.beginPath();
if (shape === 'rectangle') {
ctx.rect(startX, startY, endX - startX, endY - startY);
} else if (shape === 'circle') {
const radius = Math.sqrt(Math.pow(endX - startX, 2) + Math.pow(endY - startY, 2));
ctx.arc(startX, startY, radius, 0, Math.PI * 2);
}
ctx.stroke();
}
撤销与重做功能
使用数组保存绘图历史记录:
const history = [];
let historyIndex = -1;
function saveState() {
historyIndex++;
history.length = historyIndex;
history.push(canvas.toDataURL());
}
function undo() {
if (historyIndex <= 0) return;
historyIndex--;
const img = new Image();
img.onload = () => ctx.drawImage(img, 0, 0);
img.src = history[historyIndex];
}
保存绘图结果
添加导出图像功能:
function saveImage() {
const link = document.createElement('a');
link.download = 'drawing.png';
link.href = canvas.toDataURL('image/png');
link.click();
}
触摸屏支持
添加触摸事件处理使工具兼容移动设备:
canvas.addEventListener('touchstart', (e) => {
e.preventDefault();
const touch = e.touches[0];
const mouseEvent = new MouseEvent('mousedown', {
clientX: touch.clientX,
clientY: touch.clientY
});
canvas.dispatchEvent(mouseEvent);
});
canvas.addEventListener('touchmove', (e) => {
e.preventDefault();
const touch = e.touches[0];
const mouseEvent = new MouseEvent('mousemove', {
clientX: touch.clientX,
clientY: touch.clientY
});
canvas.dispatchEvent(mouseEvent);
});
以上代码组合可实现基础绘图工具的核心功能,包括自由绘制、图形工具、撤销重做和导出图像等特性。实际开发中可根据需求进一步扩展功能如图层管理、滤镜效果等。






