画板支持设置线条的粗细、颜色, 橡皮檫和清除功能。
效果如下图:
代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
#canvas {
border: 2px solid rgba(0, 0, 0, .4);
margin-left: 2px;
}
#lineWidth {
width: 30px;
}
.margin-bottom-10 {
margin-bottom: 10px;
}
.canvas-group {
display: flex;
justify-content: center;
}
.title {
padding: 10px;
}
.canvas-text {
width: 60px;
display: flex;
flex-direction: column;
align-items: flex-end;
}
</style>
</head>
<body style="text-align: center;">
<div class="title">简易画板</div>
<div class="canvas-group">
<div class="canvas-text">
<input class="margin-bottom-10" type="number" id="lineWidth" value="1" onchange="getColor(this)" />
<input class="margin-bottom-10" id="color" type="color" onchange="getColor(this)" />
<button class="margin-bottom-10" onclick="clearD()">橡皮檫</button>
<button onclick="clearC()">清除</button>
</div>
<canvas id="canvas" height="500" width="500">TM该浏览器不支持</canvas>
</div>
<script type="text/javascript">
let canvasD = document.getElementById('canvas');
let pen = canvasD.getContext('2d');
function setCanvas(isClear) {
if (isClear) {
pen.strokeStyle = '#fff';
} else {
pen.strokeStyle = document.getElementById('color').value || '#000';
}
pen.lineWidth = document.getElementById('lineWidth').value;
canvasD.onmousedown = function(e) {
pen.beginPath();
pen.moveTo(e.clientX - this.offsetLeft, e.clientY - this.offsetTop);
var _this = this;
document.onmousemove = function(e2) {
pen.lineTo(e2.clientX - _this.offsetLeft, e2.clientY - _this.offsetTop);
pen.stroke();
};
document.onmouseup = function() {
this.onmousemove = null;
this.onmouseup = null;
};
}
}
function clearD() {
setCanvas(1);
}
function clearC() {
pen.clearRect(0, 0, canvasD.width, canvasD.height);
}
function getColor(e) {
setCanvas()
}
setCanvas();
</script>
</body>
</html>