使用js+canvas写了个简易画板

画板支持设置线条的粗细、颜色, 橡皮檫和清除功能。

效果如下图:
在这里插入图片描述
代码

<!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>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值