h5制作自定义画板,包含选取颜色、橡皮擦清楚、变换笔画大小、清空画板、保存图片功能。
时间: 2023-10-20 13:25:50 浏览: 143
好的,以下是一个简单的实现:
HTML 代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>自定义画板</title>
<meta charset="utf-8">
<style type="text/css">
canvas {
border: 1px solid #ddd;
}
</style>
</head>
<body>
<div>
<button id="clearBtn">清空画板</button>
<button id="saveBtn">保存图片</button>
<label for="colorInput">选择颜色:</label>
<input type="color" id="colorInput">
<label for="eraserInput">橡皮擦:</label>
<input type="checkbox" id="eraserInput">
<label for="sizeInput">笔画大小:</label>
<input type="range" id="sizeInput" min="1" max="50" step="1" value="10">
</div>
<canvas id="canvas" width="800" height="600"></canvas>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
```
其中,我们用了一个 `<canvas>` 标签来实现画板,用了一些按钮和输入框来实现各种功能。
JavaScript 代码:
```javascript
// 获取 canvas 元素和上下文
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
// 设置默认画笔颜色和大小
var color = '#000';
var size = 10;
// 画板状态
var isDrawing = false;
var isErasing = false;
// 鼠标事件处理函数
function onMouseDown(event) {
isDrawing = true;
context.beginPath();
context.moveTo(event.clientX - canvas.offsetLeft, event.clientY - canvas.offsetTop);
}
function onMouseMove(event) {
if (isDrawing) {
if (isErasing) {
context.clearRect(event.clientX - canvas.offsetLeft, event.clientY - canvas.offsetTop, size, size);
} else {
context.lineTo(event.clientX - canvas.offsetLeft, event.clientY - canvas.offsetTop);
context.strokeStyle = color;
context.lineWidth = size;
context.stroke();
}
}
}
function onMouseUp(event) {
isDrawing = false;
context.closePath();
}
// 清空画板
function clearCanvas() {
context.clearRect(0, 0, canvas.width, canvas.height);
}
// 保存图片
function saveImage() {
var link = document.createElement('a');
link.download = 'canvas.png';
link.href = canvas.toDataURL();
link.click();
}
// 更新画笔颜色
var colorInput = document.getElementById('colorInput');
colorInput.addEventListener('change', function() {
color = colorInput.value;
});
// 切换橡皮擦
var eraserInput = document.getElementById('eraserInput');
eraserInput.addEventListener('change', function() {
isErasing = eraserInput.checked;
});
// 更新画笔大小
var sizeInput = document.getElementById('sizeInput');
sizeInput.addEventListener('change', function() {
size = sizeInput.value;
});
// 绑定鼠标事件处理函数
canvas.addEventListener('mousedown', onMouseDown);
canvas.addEventListener('mousemove', onMouseMove);
canvas.addEventListener('mouseup', onMouseUp);
// 绑定按钮事件处理函数
var clearBtn = document.getElementById('clearBtn');
clearBtn.addEventListener('click', clearCanvas);
var saveBtn = document.getElementById('saveBtn');
saveBtn.addEventListener('click', saveImage);
```
这段代码中,我们实现了以下功能:
- 获取 canvas 元素和上下文
- 设置默认画笔颜色和大小
- 画板状态
- 鼠标事件处理函数
- 清空画板
- 保存图片
- 更新画笔颜色
- 切换橡皮擦
- 更新画笔大小
- 绑定鼠标事件处理函数
- 绑定按钮事件处理函数
最后,我们将这些代码保存到 `script.js` 文件中,并在 HTML 中引入即可。
阅读全文