CSS样式
css
/ 重置样式 /{margin: 0;padding: 0;box-sizing: border-box;
}/ 主体部分 /
body {font-family: Arial, sans-serif;line-height: 1.6;
}/ 页眉 /
header {background-color: 333;color: fff;padding: 20px;
Text-align: center;
}h1 {margin-top: 0;
}/ 主体内容 /
main {display: grid;grid-template-columns: 1fr 1fr;gap: 20px;padding: 20px;
}/ 绘画区域 /
.painting-area {border: 1px solid ccc;border-radius: 10px;overflow: hidden;position: relative;
}canvas {width: 100%;height: 100%;
}.tools {position: absolute;top: 0;left: 0;padding: 10px;
}ul {list-style-type: none;display: flex;gap: 10px;
}button {padding: 5px 10px;border: 1px solid ccc;border-radius: 5px;cursor: pointer;
}.active {background-color: 000;color: fff;
}.brush-settings,
.color-picker {margin-top: 10px;
}label {margin-right: 5px;
}input[type="range"] {width: 100%;
}input[type="color"] {width: 60px;
}/ 画廊 /
.gallery {border: 1px solid ccc;border-radius: 10px;padding: 10px;overflow: auto;
}/ 画作 /
.painting {
width: 150px;height: 150px;margin: 10px;border: 1px solid ccc;border-radius: 10px;background-size: cover;background-position: center;
}/ 页脚 /
footer {background-color: 333;color: fff;padding: 20px;text-align: center;
}JavaScript脚本
javascript
// 获取画布元素
const canvas = document.getElementById('canvas');// 获取上下文
const ctx = canvas.getContext('2d');// 设置初始画笔大小和颜色
let brushSize = 10;
let color = '000000';// 设置工具
const brushTool = document.getElementById('brush-tool');
const eraserTool = document.getElementById('eraser-tool');
const clearCanvasButton = document.getElementById('clear-canvas-button');// 设置画笔大小
const brushSizeInput = document.getElementById('brush-size');
brushSizeInput.addEventListener('input', (e) => {brushSize = e.target.value;
});// 设置颜色
const colorPicker = document.getElementById('color-picker');
colorPicker.addEventListener('input', (e) => {color = e.target.value;
});// 激活画笔工具
brushTool.addEventListener('click', () => {ctx.strokeStyle = color;ctx.lineWidth = brushSize;
});// 激活橡皮擦工具
eraserTool.addEventListener('click', () => {
ctx.strokeStyle = 'ffffff';ctx.lineWidth = brushSize;
});// 清除画布
clearCanvasButton.addEventListener('click', () => {ctx.clearRect(0, 0, canvas.width, canvas.height);
});// 鼠标按下事件
let isMouseDown = false;
let lastX, lastY;
canvas.addEventListener('mousedown', (e) => {isMouseDown = true;lastX = e.offsetX;lastY = e.offsetY;
});// 鼠标移动事件
canvas.addEventListener('mousemove', (e) => {if (isMouseDown) {ctx.beginPath();ctx.moveTo(lastX, lastY);ctx.lineTo(e.offsetX, e.offsetY);ctx.stroke();lastX = e.offsetX;lastY = e.offsetY;}
});// 鼠标松开事件
canvas.addEventListener('mouseup', () => {isMouseDown = false;
});// 保存画作到画廊
const gallery = document.getElementById('gallery');
const saveButton = document.getElementById('save-button');
saveButton.addEventListener('click', () => {const data = canvas.toDataURL();const painting = document.createElement('div');painting.classList.add('painting');painting.style.backgroundImage = `url(${data})`;gallery.appendChild(painting);
});
发表评论